### Installing Application Executable Source: https://github.com/d-james-gh/cached_query/blob/main/packages/cached_query_flutter/example/windows/CMakeLists.txt Installs the application's runtime executable to the specified installation prefix. This makes the application runnable after installation. ```cmake install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" COMPONENT Runtime) ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/d-james-gh/cached_query/blob/main/docs/README.md Run this command to install all necessary project dependencies. ```bash $ yarn ``` -------------------------------- ### Setting Installation Directories Source: https://github.com/d-james-gh/cached_query/blob/main/packages/cached_query_flutter/example/windows/CMakeLists.txt Defines installation directories for bundle data and libraries. These paths are used to ensure files are placed correctly during the installation process. ```cmake set(BUILD_BUNDLE_DIR "$") set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1) if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) endif() set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}") ``` -------------------------------- ### Define Installation Directories Source: https://github.com/d-james-gh/cached_query/blob/main/packages/cached_query_flutter/example/linux/CMakeLists.txt Sets variables for the installation directories within the bundle, specifically for data and libraries. ```cmake set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib") ``` -------------------------------- ### Start Local Development Server Source: https://github.com/d-james-gh/cached_query/blob/main/docs/README.md Starts a local development server for live previewing changes. Changes are reflected live without server restarts. ```bash $ yarn start ``` -------------------------------- ### Installing Bundled Plugin Libraries Source: https://github.com/d-james-gh/cached_query/blob/main/packages/cached_query_flutter/example/windows/CMakeLists.txt Installs any bundled plugin libraries. This ensures that plugin dependencies are available at runtime. ```cmake if(PLUGIN_BUNDLED_LIBRARIES) install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) endif() ``` -------------------------------- ### Installing Flutter Library Source: https://github.com/d-james-gh/cached_query/blob/main/packages/cached_query_flutter/example/windows/CMakeLists.txt Installs the main Flutter library file to the bundle library directory. This is a core component for the Flutter application. ```cmake install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) ``` -------------------------------- ### Installing AOT Library Source: https://github.com/d-james-gh/cached_query/blob/main/packages/cached_query_flutter/example/windows/CMakeLists.txt Installs the Ahead-Of-Time (AOT) compiled library on non-Debug builds (Profile and Release). This optimizes application startup performance. ```cmake install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" CONFIGURATIONS Profile;Release COMPONENT Runtime) ``` -------------------------------- ### Install Bundled Plugin Libraries Source: https://github.com/d-james-gh/cached_query/blob/main/packages/cached_query_flutter/example/linux/CMakeLists.txt Installs any bundled libraries associated with plugins to the library directory within the bundle. This loop iterates through a list of bundled libraries. ```cmake foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES}) install(FILES "${bundled_library}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) endforeach(bundled_library) ``` -------------------------------- ### Set Installation Prefix for Bundle Source: https://github.com/d-james-gh/cached_query/blob/main/packages/cached_query_flutter/example/linux/CMakeLists.txt Configures the installation prefix to a 'bundle' directory within the build directory. This is used for creating a relocatable application bundle. ```cmake set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle") if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) endif() ``` -------------------------------- ### Installing Flutter Assets Source: https://github.com/d-james-gh/cached_query/blob/main/packages/cached_query_flutter/example/windows/CMakeLists.txt Installs the Flutter assets directory, ensuring all application assets are copied to the correct location. The assets directory is removed and re-copied on each build to prevent stale files. ```cmake set(FLUTTER_ASSET_DIR_NAME "flutter_assets") install(CODE " file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") " COMPONENT Runtime) install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) ``` -------------------------------- ### Clean Build Bundle Directory on Install Source: https://github.com/d-james-gh/cached_query/blob/main/packages/cached_query_flutter/example/linux/CMakeLists.txt Removes the build bundle directory before installation to ensure a clean state. This is executed as part of the installation process. ```cmake install(CODE " file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\") " COMPONENT Runtime) ``` -------------------------------- ### Create Infinite Query Repository Source: https://github.com/d-james-gh/cached_query/blob/main/docs/docs/examples/04-infinite-list-with-bloc.md Sets up an InfiniteQuery in the repository to fetch posts. It defines how to get the next page argument and maps the service response to PostModel. ```dart class PostRepository { final _service = PostService(); InfiniteQuery, int> getPosts() { return InfiniteQuery, int>( key: 'posts', getNextArg: (state) { if (state.lastPage?.isEmpty ?? false) return null; return state.length + 1; }, queryFn: (page) async => PostModel.listFromJson( await _service.getPosts(page: page, limit: 10), ), ); } } ``` -------------------------------- ### Fetch Next Page Example Source: https://github.com/d-james-gh/cached_query/blob/main/docs/docs/docs/guides/07-infinite-query.md Demonstrates how to fetch the next page of data using the getNextPage() method on an InfiniteQuery instance. The result is a future of the updated query state. ```dart final postsQuery = InfiniteQuery, int>( key: 'posts', getNextArg: (state) { if (state.lastPage?.isEmpty ?? false) return null; return state.length + 1; }, queryFn: (page) => fetchPosts(endpoint: "/api/data?page=${page}"), ); --- final nextPage = await postsQuery.getNextPage(); ``` -------------------------------- ### Installing ICU Data File Source: https://github.com/d-james-gh/cached_query/blob/main/packages/cached_query_flutter/example/windows/CMakeLists.txt Installs the ICU data file to the bundle data directory. This file is required for internationalization and localization. ```cmake install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) ``` -------------------------------- ### Define Infinite Query with Previous Page Logic Source: https://github.com/d-james-gh/cached_query/blob/main/docs/docs/docs/guides/07-infinite-query.md An example of an InfiniteQuery that defines both getNextArg and getPrevArg. getPrevArg handles fetching previous pages, returning null if it reaches the beginning. ```dart InfiniteQuery, int> getPosts() { return InfiniteQuery( key: 'posts', getNextArg: (state) { // initial arg if (state == null || state.args.isEmpty) return 5; final lastArg = state.args.last; return lastArg + 1; }, getPrevArg: (state) { final firstArg = state?.args.firstOrNull; if (firstArg == null || firstArg <= 1) return null; return firstArg - 1; }, queryFn: (arg) async { ///...fetch posts with arg }, ); } ``` -------------------------------- ### Enable Retries with Default Exponential Backoff Source: https://github.com/d-james-gh/cached_query/blob/main/docs/docs/docs/guides/10-retrying.md Add a `RetryConfig` to your `Query` to enable retries. This example retries up to 3 times with default exponential backoff. ```dart Query( key: 'posts', queryFn: () => api.getPosts(), config: QueryConfig( retryConfig: RetryConfig( maxRetries: 3, ), ), ); ``` -------------------------------- ### Install Cached Query for Dart Source: https://github.com/d-james-gh/cached_query/blob/main/docs/docs/docs/02-quick-start.md Add the base package to your Dart-only project's dependencies. ```yaml dependencies: cached_query: ^[version] ``` -------------------------------- ### Set Runtime Output Directory Source: https://github.com/d-james-gh/cached_query/blob/main/packages/cached_query_flutter/example/linux/CMakeLists.txt Places the executable in a subdirectory within the build directory to prevent accidental execution of unbundled copies. Only the installed bundle's executable will launch correctly due to resource location requirements. ```cmake set_target_properties(${BINARY_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/intermediates_do_not_run" ) ``` -------------------------------- ### Install Cached Query for Flutter Source: https://github.com/d-james-gh/cached_query/blob/main/docs/docs/docs/02-quick-start.md Add the Flutter-specific package to your Flutter project's dependencies. ```yaml dependencies: cached_query_flutter: ^[version] ``` -------------------------------- ### Set Minimum CMake Version and Project Name Source: https://github.com/d-james-gh/cached_query/blob/main/packages/cached_query_flutter/example/linux/CMakeLists.txt Specifies the minimum required CMake version and the project name. This is a standard starting point for any CMake project. ```cmake cmake_minimum_required(VERSION 3.10) project(runner LANGUAGES CXX) ``` -------------------------------- ### Install Cached Query Flutter Source: https://github.com/d-james-gh/cached_query/blob/main/docs/docs/examples/01-simple-query.md Add the cached_query_flutter package to your Flutter project dependencies. ```bash flutter pub add cached_query_flutter ``` -------------------------------- ### Example Widget Structure Source: https://github.com/d-james-gh/cached_query/blob/main/docs/docs/docs/02-migration-v2-v3/_query-state.mdx This snippet shows a typical widget structure within a Flutter application, likely part of a UI that displays query results. It includes conditional rendering based on query status. ```dart textAlign: TextAlign.center, ), ], ), ), _ => const SizedBox(), }; }, ); } } ``` ``` -------------------------------- ### Configure Cached Query Flutter (After) Source: https://github.com/d-james-gh/cached_query/blob/main/docs/docs/docs/02-migration-v2-v3/_config-changes.mdx Example of configuring Cached Query Flutter with global settings and multiple observers after the update. Ensure WidgetsFlutterBinding is initialized. ```dart void main() async { WidgetsFlutterBinding.ensureInitialized(); CachedQuery.instance.configFlutter( config: GlobalQueryConfigFlutter( refetchOnResume: true, ), storage: await CachedStorage.ensureInitialized(), observers: [ Observer(), QueryLoggingObserver(colors: !Platform.isIOS), ], ); runApp(const MyApp()); } ``` -------------------------------- ### Configure Cached Query Flutter (Before) Source: https://github.com/d-james-gh/cached_query/blob/main/docs/docs/docs/02-migration-v2-v3/_config-changes.mdx Example of configuring Cached Query Flutter with query-specific settings before the update. ```dart void main() { CachedQuery.instance.configFlutter( config: QueryConfigFlutter( refetchDuration: Duration(seconds: 4), ), storage: await CachedStorage.ensureInitialized(), ); runApp(MyApp()); } ``` -------------------------------- ### Define Flutter Library Path Source: https://github.com/d-james-gh/cached_query/blob/main/packages/cached_query_flutter/example/windows/flutter/CMakeLists.txt Sets the path to the Flutter Windows DLL. This variable is published to the parent scope for use in the install step. ```cmake set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll") # Published to parent scope for install step. set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) ``` -------------------------------- ### Install Cached Query Packages Source: https://github.com/d-james-gh/cached_query/blob/main/packages/cached_query/README.md Add the cached_query, cached_query_flutter, or cached_storage packages to your pubspec.yaml file depending on your project needs. ```yaml dependencies: # Use either cached_query or cached_query_flutter depending on your project # both is unnecessary as cached_query_flutter exports cached_query cached_query: [version] cached_query_flutter: [version] cached_storage: [version] ``` -------------------------------- ### Configure Flutter Library and Headers Source: https://github.com/d-james-gh/cached_query/blob/main/packages/cached_query_flutter/example/linux/flutter/CMakeLists.txt Defines the path to the Flutter Linux GTK shared library and ICU data file. It also sets up the project build directory and the AOT (Ahead-Of-Time) compiled library path, publishing these to the parent scope for use in installation steps. ```cmake set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/libflutter_linux_gtk.so") # Published to parent scope for install step. set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) set(AOT_LIBRARY "${PROJECT_DIR}/build/lib/libapp.so" PARENT_SCOPE) ``` -------------------------------- ### Configure Cached Query Globally Source: https://github.com/d-james-gh/cached_query/blob/main/packages/cached_query/README.md Set up a default configuration for Cached Query, including storage and global query settings like staleDuration and cacheDuration. This should be done once at the application's start. ```dart void main() async { CachedQuery.instance.config( storage: await CachedStorage.ensureInitialized(), config: GlobalQueryConfig( staleDuration: Duration(seconds: 4), cacheDuration: Duration(minutes: 5), ), ); } ``` -------------------------------- ### Conditional AOT Library Installation in CMake Source: https://github.com/d-james-gh/cached_query/blob/main/packages/cached_query_flutter/example/linux/CMakeLists.txt Use this CMake snippet to install the AOT library only when the build type is not Debug. Ensure the AOT_LIBRARY variable and installation paths are correctly defined. ```cmake if(NOT CMAKE_BUILD_TYPE MATCHES "Debug") install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) endif() ``` -------------------------------- ### Post List UI with BlocProvider Source: https://github.com/d-james-gh/cached_query/blob/main/docs/docs/examples/04-infinite-list-with-bloc.md Sets up the UI for a post list page using BlocProvider. It initializes the PostWithBuilderBloc and provides the initial data fetch event. Navigation actions are included for switching between list views. ```dart class PostListWithBuilderPage extends StatelessWidget { static const routeName = 'postWithBuilderList'; const PostListWithBuilderPage({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return BlocProvider( create: (_) => PostWithBuilderBloc()..add(PostsWithBuilderFetched()), child: Scaffold( appBar: AppBar( title: const Text("Posts With Builder"), actions: [ IconButton( icon: const Icon(Icons.arrow_right_alt), onPressed: () => Navigator.pushReplacementNamed( context, PostListPage.routeName, ), ) ], ), body: const _List(), ), ); } } ``` -------------------------------- ### Build Static Website Content Source: https://github.com/d-james-gh/cached_query/blob/main/docs/README.md Generates the static content for the website into the 'build' directory, ready for hosting. ```bash $ yarn build ``` -------------------------------- ### Configure Cross-Building Sysroot Source: https://github.com/d-james-gh/cached_query/blob/main/packages/cached_query_flutter/example/linux/CMakeLists.txt Sets up the sysroot and find root path for cross-compilation. This is used when building for a different platform than the host system. ```cmake if(FLUTTER_TARGET_PLATFORM_SYSROOT) set(CMAKE_SYSROOT ${FLUTTER_TARGET_PLATFORM_SYSROOT}) set(CMAKE_FIND_ROOT_PATH ${CMAKE_SYSROOT}) set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY) set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) endif() ``` -------------------------------- ### Apply Standard Build Settings Source: https://github.com/d-james-gh/cached_query/blob/main/packages/cached_query_flutter/example/windows/runner/CMakeLists.txt Applies a predefined set of standard build settings to the executable target. This can be customized or removed if different build configurations are required. ```cmake # Apply the standard set of build settings. This can be removed for applications # that need different build settings. apply_standard_settings(${BINARY_NAME}) ``` -------------------------------- ### Get Query from Cache Source: https://github.com/d-james-gh/cached_query/blob/main/docs/docs/docs/guides/06-global-cache.md Retrieve a query or infinite query from the cache using its key. ```dart CachedQuery.instance.getQuery(key); ``` -------------------------------- ### Add Dependencies and Include Directories Source: https://github.com/d-james-gh/cached_query/blob/main/packages/cached_query_flutter/example/windows/runner/CMakeLists.txt Links necessary libraries (flutter, flutter_wrapper_app) and specifies include directories for the project. Application-specific dependencies should be added here. ```cmake # Add dependency libraries and include directories. Add any application-specific # dependencies here. target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app) target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") ``` -------------------------------- ### Deploy Website via SSH Source: https://github.com/d-james-gh/cached_query/blob/main/docs/README.md Builds the website and deploys it to the gh-pages branch using SSH. Assumes GitHub pages hosting. ```bash $ USE_SSH=true yarn deploy ``` -------------------------------- ### Load Flutter Entrypoint and Initialize Engine Source: https://github.com/d-james-gh/cached_query/blob/main/packages/cached_query_flutter/example/web/index.html This script is injected by Flutter build. It loads the main Dart entry point, initializes the Flutter engine, and runs the application. Ensure `serviceWorkerVersion` is correctly set. ```javascript var serviceWorkerVersion = null; window.addEventListener('load', function(ev) { // Download main.dart.js _flutter.loader.loadEntrypoint({ serviceWorker: { serviceWorkerVersion: serviceWorkerVersion, } }).then(function(engineInitializer) { return engineInitializer.initializeEngine(); }).then(function(appRunner) { return appRunner.runApp(); }); }); ``` -------------------------------- ### PostWithBuilderBloc Implementation Source: https://github.com/d-james-gh/cached_query/blob/main/docs/docs/examples/04-infinite-list-with-bloc.md This Bloc is responsible for streaming the infinite query directly to the UI. It initializes the query and handles fetching new pages. ```dart class PostWithBuilderBloc extends Bloc { final _repo = PostRepository(); PostWithBuilderBloc() : super(PostWithBuilderInitial()) { on(_onPostsFetched); on(_onPostsNextPage); } FutureOr _onPostsFetched( PostsWithBuilderFetched _, Emitter emit, ) { final query = _repo.getPosts(); emit(PostWithBuilderSuccess(postQuery: query)); } void _onPostsNextPage( PostWithBuilderEvent _, Emitter __ ) { // No need to store the query in a variable as calling getPosts() again will // retrieve the same instance of infinite query. _repo.getPosts().getNextPage(); } } ``` -------------------------------- ### Conditional Retries Based on Error Type Source: https://github.com/d-james-gh/cached_query/blob/main/docs/docs/docs/guides/10-retrying.md Use the `whenError` predicate in `RetryConfig` to control which errors trigger a retry. This example only retries `NetworkException` errors. ```dart RetryConfig( maxRetries: 3, whenError: (error, attempt) => error is NetworkException, ) ``` -------------------------------- ### Initialize QueryConfig Source: https://github.com/d-james-gh/cached_query/blob/main/docs/docs/docs/guides/04-configuration.md Set up a new QueryConfig with specific durations, storage options, and behavior flags. Use this to customize individual query caching and refetching logic. ```dart final config = QueryConfig( storageSerializer: null, storageDeserializer: null, ignoreCacheDuration: false, storeQuery: true, staleDuration: Duration(seconds: 4), cacheDuration: Duration(minutes: 5), shouldRethrow: false, shouldRefetch: null, ); ``` -------------------------------- ### MyApp Widget Configuration Source: https://github.com/d-james-gh/cached_query/blob/main/docs/docs/examples/04-infinite-list-with-bloc.md The root `MyApp` widget defines application routes, including `PostListPage` and `PostListWithBuilderPage`. Ensure these routes are correctly registered. ```dart class MyApp extends StatelessWidget { const MyApp({super.key}); // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', routes: { PostListPage.routeName: (_) => const PostListPage(), PostListWithBuilderPage.routeName: (_) => const PostListWithBuilderPage(), }, ); } } ``` -------------------------------- ### Post Page UI with BlocProvider Source: https://github.com/d-james-gh/cached_query/blob/main/docs/docs/examples/02-with-flutter-bloc.md This UI component sets up the PostBloc using `BlocProvider` and dispatches an initial `PostFetched` event. It uses `BlocSelector` to display loading states and `BlocBuilder` to render navigation controls and the post content, reacting to state changes from the Bloc. ```dart class PostPage extends StatelessWidget { const PostPage({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return BlocProvider( create: (context) => PostBloc()..add(PostFetched(50)), child: Builder(builder: (context) { return Scaffold( appBar: AppBar( centerTitle: true, title: BlocSelector( selector: (state) => state.isLoading, builder: (context, isLoading) { return Text( isLoading ? "loading..." : "", ); }, ), actions: [ IconButton( icon: const Icon(Icons.refresh), onPressed: () => context.read().add(PostRefreshed()), ) ], ), body: Center( child: Column( children: [ BlocBuilder( builder: (context, state) { final currentId = state.currentId; return Row( mainAxisAlignment: MainAxisAlignment.center, children: [ IconButton( onPressed: () => context .read() .add(PostFetched(currentId - 1)), icon: const Icon(Icons.arrow_left), ), Text(currentId.toString()), IconButton( onPressed: () => context .read() .add(PostFetched(currentId + 1)), icon: const Icon(Icons.arrow_right), ), ], ); }, ), BlocSelector( selector: (state) => state.post, builder: (context, post) { if (post == null) { return const SizedBox(); } return Post(post: post); }, ), ], ), ), ); }), ); } } ``` -------------------------------- ### Basic Query Initialization Source: https://github.com/d-james-gh/cached_query/blob/main/docs/docs/docs/guides/03-query.md Initialize a Query with a key, initial data, and a query function. The queryFn is an asynchronous function that fetches data. ```dart final query = Query( key: "my_data", initialData: "Pre-populated data", queryFn: () => api.getData(), ); ``` -------------------------------- ### Create Static Plugin Wrapper Library Source: https://github.com/d-james-gh/cached_query/blob/main/packages/cached_query_flutter/example/windows/flutter/CMakeLists.txt Creates a static library for the C++ plugin wrapper. It includes core and plugin-specific sources and links against the Flutter library. ```cmake add_library(flutter_wrapper_plugin STATIC ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} ) apply_standard_settings(flutter_wrapper_plugin) set_target_properties(flutter_wrapper_plugin PROPERTIES POSITION_INDEPENDENT_CODE ON) set_target_properties(flutter_wrapper_plugin PROPERTIES CXX_VISIBILITY_PRESET hidden) target_link_libraries(flutter_wrapper_plugin PUBLIC flutter) target_include_directories(flutter_wrapper_plugin PUBLIC "${WRAPPER_ROOT}/include" ) add_dependencies(flutter_wrapper_plugin flutter_assemble) ``` -------------------------------- ### Define C++ Wrapper App Sources Source: https://github.com/d-james-gh/cached_query/blob/main/packages/cached_query_flutter/example/windows/flutter/CMakeLists.txt Lists the C++ source files for the application wrapper. Paths are prefixed with the wrapper root directory. ```cmake list(APPEND CPP_WRAPPER_SOURCES_APP "flutter_engine.cc" "flutter_view_controller.cc" ) list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/") ``` -------------------------------- ### Create Query for Fetching Source: https://github.com/d-james-gh/cached_query/blob/main/docs/docs/docs/guides/06-global-cache.md To enable fetching after using `setQueryData`, create a `Query` or `InfiniteQuery` with the same key. ```dart final query = Query( key: "query_key", queryFn: (_) async => "", ); // WILL NOT FAIL query.refetch(); ``` ```dart final query = InfiniteQuery( key: "query_key", getNextArg: (state) => (state?.length ?? 0) + 1, queryFn: (_) async => "", ); // WILL NOT FAIL query.refetch(); ``` -------------------------------- ### Create Static Application Wrapper Library Source: https://github.com/d-james-gh/cached_query/blob/main/packages/cached_query_flutter/example/windows/flutter/CMakeLists.txt Creates a static library for the C++ application wrapper. It includes core and application-specific sources and links against the Flutter library. ```cmake add_library(flutter_wrapper_app STATIC ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_APP} ) apply_standard_settings(flutter_wrapper_app) target_link_libraries(flutter_wrapper_app PUBLIC flutter) target_include_directories(flutter_wrapper_app PUBLIC "${WRAPPER_ROOT}/include" ) add_dependencies(flutter_wrapper_app flutter_assemble) ``` -------------------------------- ### Get Cached Data with Future API Source: https://github.com/d-james-gh/cached_query/blob/main/packages/cached_query/README.md Use the Query.result API to fetch data. The data is cached against the provided key. Subsequent calls with the same key will return cached data immediately. ```dart Future getCachedData() async { final query = Query(key: "My key", queryFn: fetchData); final queryState = await query.result; return queryState.data; } ``` -------------------------------- ### Listen to Query Stream for Real-time Updates Source: https://github.com/d-james-gh/cached_query/blob/main/packages/cached_query/README.md Use the Query.stream API to get a stream of QueryStatus objects. This allows your UI to react to loading states, background fetches, and cache updates in real-time. ```dart Stream> getCachedData() async { final query = Query(key: "My key", queryFn: fetchData); return query.stream; } ``` -------------------------------- ### Apply Standard Settings to Executable Source: https://github.com/d-james-gh/cached_query/blob/main/packages/cached_query_flutter/example/linux/CMakeLists.txt Applies the standard build settings defined in the APPLY_STANDARD_SETTINGS function to the application executable. This can be removed if the application requires different build settings. ```cmake apply_standard_settings(${BINARY_NAME}) ``` -------------------------------- ### Include Generated Configuration Source: https://github.com/d-james-gh/cached_query/blob/main/packages/cached_query_flutter/example/windows/flutter/CMakeLists.txt Includes a generated configuration file that provides build-time settings. This file is expected to be present in the ephemeral directory. ```cmake include(${EPHEMERAL_DIR}/generated_config.cmake) ``` -------------------------------- ### Post Widget (Before) Source: https://github.com/d-james-gh/cached_query/blob/main/docs/docs/docs/02-migration-v2-v3/_query-state.mdx Initial implementation of the Post widget using QueryBuilder without explicit state sealing. ```dart class Post extends StatelessWidget { final int id; const Post({required this.id, super.key}); @override Widget build(BuildContext context) { return QueryBuilder( // Can use key if the query already exists. queryKey: service.postKey(id), builder: (context, state) { final data = state.data; if (state.error != null) return Text(state.error.toString()); if (data == null) return const SizedBox(); return Container( margin: const EdgeInsets.all(10), child: Column( children: [ const Text( "Title", textAlign: TextAlign.center, style: TextStyle(fontSize: 20), ), Text( data.title, textAlign: TextAlign.center, ), const Text( "Body", textAlign: TextAlign.center, style: TextStyle(fontSize: 20), ), Text( data.body, textAlign: TextAlign.center, ), ], ), ); }, ); } } ``` -------------------------------- ### Update Queries Using String Prefix Filter Source: https://github.com/d-james-gh/cached_query/blob/main/docs/docs/docs/guides/06-global-cache.md Use a filter function to update all cached queries whose keys start with a specific string. This is useful for batch updates on related data, like a list of todos. ```dart CachedQuery.instance.updateQuery( updateFn: (dynamic oldData){ if(oldData is Todo){ return oldData?.copyWith(complete: true); } }, filterFn: (unencodedKey, key) => key.startsWith("todos/"), ); ``` -------------------------------- ### Infinite Query UI with CustomScrollView Source: https://github.com/d-james-gh/cached_query/blob/main/docs/docs/examples/03-infinite-query.md Builds the main list UI using InfiniteQueryBuilder, displaying posts and handling different query states like error and loading. It uses CustomScrollView with SliverList for efficient rendering. ```dart InfiniteQueryBuilder, int>( query: getPosts(), builder: (context, state, query) { final allPosts = state.data?.expand((e) => e).toList(); return CustomScrollView( controller: _scrollController, slivers: [ if (state.status == QueryStatus.error) SliverToBoxAdapter( child: DecoratedBox( decoration: BoxDecoration(color: Theme.of(context).errorColor), child: Text( state.error is SocketException ? "No internet connection" : state.error.toString(), style: const TextStyle(color: Colors.white), textAlign: TextAlign.center, ), ), ), if (allPosts != null) SliverList( delegate: SliverChildBuilderDelegate( (context, i) => Post( post: allPosts[i], index: i, ), childCount: allPosts.length, ), ), if (state.status == QueryStatus.loading) const SliverToBoxAdapter( child: Center( child: SizedBox( height: 40, width: 40, child: CircularProgressIndicator(), ), ), ), SliverPadding( padding: EdgeInsets.only( bottom: MediaQuery.of(context).padding.bottom ), ) ], ); }), ``` -------------------------------- ### Bloc for Fetching and Managing Posts Source: https://github.com/d-james-gh/cached_query/blob/main/docs/docs/examples/04-infinite-list-with-bloc.md This Bloc uses `emit.forEach` to subscribe to an infinite query stream and map its states to the Bloc's state. It requires the `restartable` event transformer to handle multiple `PostsFetched` events concurrently. Ensure `PostRepository` is initialized. ```dart class PostBloc extends Bloc { final _repo = PostRepository(); PostBloc() : super(const PostState()) { // use restartable on(_onPostsFetched, transformer: restartable()); on(_onPostsNextPage); } FutureOr _onPostsFetched( PostsFetched event, Emitter emit, ) { final query = _repo.getPosts(); // Subscribe to the stream from the infinite query. return emit.forEach>>( query.stream, onData: (queryState) { return state.copyWith( posts: queryState.data?.expand((page) => page).toList() ?? [], status: queryState.status == QueryStatus.loading ? PostStatus.loading : PostStatus.success, hasNextPage: queryState.hasNextPage, ); }, ); } void _onPostsNextPage(PostEvent _, Emitter __) { // No need to store the query in a variable as calling getPosts() again will // retrieve the same instance of infinite query. _repo.getPosts().getNextPage(); } } ``` -------------------------------- ### Define Infinite Post Query Source: https://github.com/d-james-gh/cached_query/blob/main/docs/docs/examples/03-infinite-query.md Sets up an InfiniteQuery to fetch posts, including cache configuration, pagination logic, and data deserialization for persistence. ```dart InfiniteQuery, int> getPosts() { return InfiniteQuery, int>( key: 'posts', config: QueryConfig( refetchDuration: const Duration(seconds: 2), // use a serializer for cached storage storageDeserializer: (dynamic postJson) { return (postJson as List) .map( (dynamic page) => PostModel.listFromJson(page as List), ) .toList(); }, ), getNextArg: (state) { if (state.lastPage?.isEmpty ?? false) return null; return state.length + 1; }, queryFn: (arg) async { final uri = Uri.parse( 'https://jsonplaceholder.typicode.com/posts?_limit=10&_page=$arg', ); final res = await http.get(uri); return PostModel.listFromJson( List>.from( jsonDecode(res.body) as List, ), ); }, ); } ``` -------------------------------- ### Refetch Queries by Keys Source: https://github.com/d-james-gh/cached_query/blob/main/docs/docs/docs/guides/06-global-cache.md Refetch multiple queries at once by providing a list of their keys. This forces a re-fetch, ignoring the stale duration. ```dart CachedQuery.instance.refetchQueries(keys: ["posts"]); ``` -------------------------------- ### Bloc Implementation with emit.foreach Source: https://github.com/d-james-gh/cached_query/blob/main/docs/docs/examples/02-with-flutter-bloc.md This Bloc implementation uses `emit.forEach` to manage query state updates and `restartable` transformer for efficient subscription handling. It maps query states to Bloc states, updating the UI when data changes or loading states occur. ```dart class PostBloc extends Bloc { PostBloc() : super(const PostState()) { /// !important: use the restartable transformer to automatically subscribe and /// unsubscribe when a new event comes in. on(_onFetched, transformer: restartable()); on(_onRefresh); } FutureOr _onFetched( PostFetched event, Emitter emit, ) { return emit.forEach( getPostById(event.id).stream, onData: (queryState) { return PostState( currentId: event.id, post: queryState.data, isLoading: queryState.status == QueryStatus.loading, ); }, ); } FutureOr _onRefresh(PostRefreshed event, Emitter emit) { getPostById(state.currentId).refetch(); } } ``` -------------------------------- ### Find and Link GTK Libraries Source: https://github.com/d-james-gh/cached_query/blob/main/packages/cached_query_flutter/example/linux/flutter/CMakeLists.txt This section uses PkgConfig to find and check for the required GTK libraries (gtk+-3.0, glib-2.0, gio-2.0). These are essential for the GTK backend of Flutter on Linux. ```cmake # System-level dependencies. find_package(PkgConfig REQUIRED) pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) pkg_check_modules(GLIB REQUIRED IMPORTED_TARGET glib-2.0) pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0) ``` -------------------------------- ### PostListScreen State Management Source: https://github.com/d-james-gh/cached_query/blob/main/docs/docs/examples/03-infinite-query.md Defines the main screen widget for displaying a list of posts, including initializing and disposing of the scroll controller and attaching the scroll listener. ```dart class PostListScreen extends StatefulWidget { static const routeName = '/'; const PostListScreen({Key? key}) : super(key: key); @override State createState() => _PostListScreenState(); } class _PostListScreenState extends State { final _scrollController = ScrollController(); @override void initState() { super.initState(); _scrollController.addListener(_onScroll); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: InfiniteQueryBuilder( queryKey: 'posts', builder: (context, state, _) { return Row( children: [ if (state.status == QueryStatus.loading) const CircularProgressIndicator( valueColor: AlwaysStoppedAnimation(Colors.white), ), const Text('posts'), ], ); }, ), centerTitle: true, ), body: InfiniteQueryBuilder, int>( query: getPosts(), builder: (context, state, query) { final allPosts = state.data?.expand((e) => e).toList(); return CustomScrollView( controller: _scrollController, slivers: [ if (state.status == QueryStatus.error) SliverToBoxAdapter( child: DecoratedBox( decoration: ``` -------------------------------- ### Define Post Service for Fetching Source: https://github.com/d-james-gh/cached_query/blob/main/docs/docs/examples/04-infinite-list-with-bloc.md A service class to fetch paginated posts from an API. Includes a simulated delay for caching demonstration. ```dart class PostService { Future> getPosts({ required int limit, required int page, }) async { final uri = Uri.parse( 'https://jsonplaceholder.typicode.com/posts?_limit=$limit&_page=$page', ); final res = await http.get(uri); // extra delay for testing purposes return Future.delayed( const Duration(seconds: 1), () => jsonDecode(res.body) as List, ); } } ``` -------------------------------- ### Define C++ Wrapper Core Sources Source: https://github.com/d-james-gh/cached_query/blob/main/packages/cached_query_flutter/example/windows/flutter/CMakeLists.txt Lists the core C++ source files for the wrapper. Paths are prefixed with the wrapper root directory. ```cmake list(APPEND CPP_WRAPPER_SOURCES_CORE "core_implementations.cc" "standard_codec.cc" ) list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/") ``` -------------------------------- ### Create and Configure a New Cache Instance Source: https://github.com/d-james-gh/cached_query/blob/main/docs/docs/docs/guides/03-query.md Instantiate a new CachedQuery instance and configure it for Flutter. This allows for isolated cache management. ```dart final cache = CachedQuery.asNewInstance() ..configFlutter(); ``` -------------------------------- ### Post Page UI with QueryBuilder Source: https://github.com/d-james-gh/cached_query/blob/main/docs/docs/examples/01-simple-query.md Builds the UI for displaying post data, using QueryBuilder to react to query state changes. It includes navigation to change the post ID and a refresh button. ```dart class PostPage extends StatefulWidget { const PostPage({Key? key}) : super(key: key); @override State createState() => _PostPageState(); } class _PostPageState extends State { int currentId = 50; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( centerTitle: true, title: QueryBuilder( query: service.getPostById(currentId), builder: (context, state) { return Text( state.status == QueryStatus.loading ? "loading..." : "", ); }, ), actions: [ IconButton( icon: const Icon(Icons.refresh), onPressed: _refreshPost, ) ], ), body: Center( child: Column( children: [ Row( mainAxisAlignment: MainAxisAlignment.center, children: [ IconButton( onPressed: () => setState(() => currentId = currentId - 1), icon: const Icon(Icons.arrow_left), ), Text(currentId.toString()), IconButton( onPressed: () => setState(() => currentId = currentId + 1), icon: const Icon(Icons.arrow_right), ), ], ), Post(id: currentId), ], ), ), ); } void _refreshPost() { service.getPostById(currentId).refetch(); } } ``` -------------------------------- ### Define C++ Wrapper Plugin Sources Source: https://github.com/d-james-gh/cached_query/blob/main/packages/cached_query_flutter/example/windows/flutter/CMakeLists.txt Lists the C++ source files specific to the plugin wrapper. Paths are prefixed with the wrapper root directory. ```cmake list(APPEND CPP_WRAPPER_SOURCES_PLUGIN "plugin_registrar.cc" ) list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/") ``` -------------------------------- ### Root App Widget Source: https://github.com/d-james-gh/cached_query/blob/main/docs/docs/examples/01-simple-query.md The main widget for the Flutter application, setting up the MaterialApp and pointing to the PostPage. ```dart class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); // This widget is the root of your application. @override Widget build(BuildContext context) { return const MaterialApp( title: 'Flutter Demo', home: PostPage(), ); } } ``` -------------------------------- ### Create Post Mutation with Optimistic Update Source: https://github.com/d-james-gh/cached_query/blob/main/docs/docs/docs/guides/08-optimistic-updates.md Use `onStartMutation` to optimistically update an infinite list by adding a new post to the beginning. A snapshot of the current data is taken as a fallback for `onError`. `invalidateQueries` ensures the list is refetched upon successful mutation. ```dart Mutation createPost() { return Mutation( key: "createPost", invalidateQueries: ['posts'], mutationFn: (post) async { final res = await Future.delayed( const Duration(milliseconds: 400), () => { "id": 123, "title": post.title, "userId": post.userId, "body": post.body, }, ); return PostModel.fromJson(res); }, onStartMutation: (newPost) { final query = CachedQuery.instance .getQuery, int>>("posts"); final fallback = query?.state.data; query?.update( (old) { return InfiniteQueryData( args: old?.args ?? [], pages: [ [newPost, ...?old?.pages.first], ...?old?.pages.sublist(1), ], ); }, ); return fallback; }, onError: (arg, error, fallback) { if (fallback != null) { CachedQuery.instance .getQuery, int>>("posts") ?.update( (old) => fallback as InfiniteQueryData, int>, ); } }, ); } ``` -------------------------------- ### Set Runtime Path for Bundled Libraries Source: https://github.com/d-james-gh/cached_query/blob/main/packages/cached_query_flutter/example/linux/CMakeLists.txt Configures the runtime search path for libraries to include the 'lib/' directory relative to the binary. This is essential for loading bundled libraries correctly. ```cmake set(CMAKE_INSTALL_RPATH "$ORIGIN/lib") ``` -------------------------------- ### Deploy Website without SSH Source: https://github.com/d-james-gh/cached_query/blob/main/docs/README.md Builds the website and deploys it to the gh-pages branch without using SSH. Requires specifying your GitHub username. ```bash $ GIT_USER= yarn deploy ``` -------------------------------- ### Link Application Libraries Source: https://github.com/d-james-gh/cached_query/blob/main/packages/cached_query_flutter/example/linux/CMakeLists.txt Links the application executable against the Flutter library and the GTK+ 3.0 library. Add any other application-specific dependencies here. ```cmake target_link_libraries(${BINARY_NAME} PRIVATE flutter) target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK) ``` -------------------------------- ### Opting into Modern CMake Behaviors Source: https://github.com/d-james-gh/cached_query/blob/main/packages/cached_query_flutter/example/windows/CMakeLists.txt Explicitly enables modern CMake behaviors to avoid warnings in recent CMake versions. This is a best practice for compatibility. ```cmake cmake_policy(SET CMP0063 NEW) ``` -------------------------------- ### Basic Flutter App with Cached Query Source: https://github.com/d-james-gh/cached_query/blob/main/docs/docs/docs/02-quick-start.md Demonstrates initializing Cached Query with offline storage and configuring global query defaults. It then sets up a simple Flutter app with a Query widget to fetch and display data. ```dart import 'package:cached_query_flutter/cached_query_flutter.dart'; import 'package:cached_storage/cached_storage.dart'; import 'package:flutter/material.dart'; import "my_api.dart" as api; void main() async { // Optionally set global query defaults. CachedQuery.instance.configFlutter( // Initialize Cached Storage to persist the cache to disk storage: await CachedStorage.ensureInitialized(), // Set global query defaults (optional) config: GlobalQueryConfigFlutter( staleDuration: const Duration(seconds: 5), cacheDuration: const Duration(minutes: 5), ), ); runApp(const MyApp()); } class MyApp extends StatefulWidget { const MyApp({Key? key}) : super(key: key); @override State createState() => _MyAppState(); } class _MyAppState extends State { final query = Query( queryFn: api.fetchData, key: ["title"], ); @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( body: Center( child: QueryBuilder( query: query, builder: (context, state) => Column( children: [ if (state.data != null) Text(state.data), if (state.isLoading) const SizedBox( height: 30, width: 30, child: CircularProgressIndicator(), ), if (state.isError) const Text("An error occurred"), ], ), ), ), ), ); } } ``` -------------------------------- ### Enable Refetch on Connection for Individual Query Source: https://github.com/d-james-gh/cached_query/blob/main/docs/docs/docs/03-flutter-additions.md Configure a specific query to refetch when the network connection is restored, overriding global settings if necessary. ```dart Query( key: "a query key", queryFn: () async => _api.getData(), config: QueryConfigFlutter( refetchOnResume: false, refetchOnConnection: true, ), ), ``` -------------------------------- ### Implement a Custom QueryObserver Source: https://github.com/d-james-gh/cached_query/blob/main/docs/docs/docs/guides/09-observer.md Extend the QueryObserver class to create a custom observer. Override methods like `onChange` to react to state changes in queries. ```dart class Observer extends QueryObserver { @override void onChange( Cachable query, QueryState nextState, ) { debugPrint(nextState.status.toString()); super.onChange(query, nextState); } } ``` -------------------------------- ### Create Post Query Source: https://github.com/d-james-gh/cached_query/blob/main/docs/docs/examples/02-with-flutter-bloc.md Defines a query to fetch a post by its ID, including a simulated network delay. ```dart Query getPostById(int id) { return Query( key: postKey(id), queryFn: () async { final uri = Uri.parse( 'https://jsonplaceholder.typicode.com/posts/$id', ); final res = await http.get(uri); return Future.delayed( const Duration(milliseconds: 500), () => PostModel.fromJson( jsonDecode(res.body) as Map, ), ); }, ); } ``` -------------------------------- ### Define a Query for JokeModel Source: https://github.com/d-james-gh/cached_query/blob/main/packages/cached_query_flutter/README.md Defines a query to fetch a JokeModel. Ensure JokeModel has a fromJson factory constructor and _service is accessible. ```dart Query getJoke() { return Query( key: 'joke', queryFn: () async => JokeModel.fromJson(await _service.getJoke()), ); } ``` -------------------------------- ### Define Flutter Library Headers Source: https://github.com/d-james-gh/cached_query/blob/main/packages/cached_query_flutter/example/linux/flutter/CMakeLists.txt Lists all the necessary header files for the Flutter Linux GTK library. These headers are then prepended with the ephemeral directory path using the custom list_prepend function. ```cmake list(APPEND FLUTTER_LIBRARY_HEADERS "fl_basic_message_channel.h" "fl_binary_codec.h" "fl_binary_messenger.h" "fl_dart_project.h" "fl_engine.h" "fl_json_message_codec.h" "fl_json_method_codec.h" "fl_message_codec.h" "fl_method_call.h" "fl_method_channel.h" "fl_method_codec.h" "fl_method_response.h" "fl_plugin_registrar.h" "fl_plugin_registry.h" "fl_standard_message_codec.h" "fl_standard_method_codec.h" "fl_string_codec.h" "fl_value.h" "fl_view.h" "flutter_linux.h" ) list_prepend(FLUTTER_LIBRARY_HEADERS "${EPHEMERAL_DIR}/flutter_linux/") ``` -------------------------------- ### Post Fetching Events for InfiniteQueryBuilder Source: https://github.com/d-james-gh/cached_query/blob/main/docs/docs/examples/04-infinite-list-with-bloc.md Defines events for fetching the initial list and the next page when using InfiniteQueryBuilder. These events are used to trigger data fetching operations. ```dart @immutable abstract class PostWithBuilderEvent {} class PostsWithBuilderFetched extends PostWithBuilderEvent {} class PostsWithBuilderNextPage extends PostWithBuilderEvent {} ``` -------------------------------- ### Find PkgConfig and GTK Dependency Source: https://github.com/d-james-gh/cached_query/blob/main/packages/cached_query_flutter/example/linux/CMakeLists.txt Finds the PkgConfig module and checks for the GTK+ 3.0 library. This is required for applications that depend on GTK. ```cmake find_package(PkgConfig REQUIRED) pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) ``` -------------------------------- ### Define Project Build Directory Source: https://github.com/d-james-gh/cached_query/blob/main/packages/cached_query_flutter/example/windows/flutter/CMakeLists.txt Sets the project's build directory path. This variable is published to the parent scope. ```cmake set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) ``` -------------------------------- ### Including Generated Plugin Rules Source: https://github.com/d-james-gh/cached_query/blob/main/packages/cached_query_flutter/example/windows/CMakeLists.txt Includes the CMake rules for generated plugins. This ensures that all necessary plugins are built and linked into the application. ```cmake include(flutter/generated_plugins.cmake) ``` -------------------------------- ### Enabling Unicode Support Source: https://github.com/d-james-gh/cached_query/blob/main/packages/cached_query_flutter/example/windows/CMakeLists.txt Adds definitions to enable Unicode support in the project. This is important for handling international characters correctly. ```cmake add_definitions(-DUNICODE -D_UNICODE) ``` -------------------------------- ### Project and Minimum CMake Version Source: https://github.com/d-james-gh/cached_query/blob/main/packages/cached_query_flutter/example/windows/CMakeLists.txt Sets the minimum required CMake version and the project name. Ensure your CMake version meets this requirement. ```cmake cmake_minimum_required(VERSION 3.14) project(example LANGUAGES CXX) ``` -------------------------------- ### Configure Global Flutter Settings Source: https://github.com/d-james-gh/cached_query/blob/main/docs/docs/docs/03-flutter-additions.md Globally configure Cached Query for Flutter applications. Ensure storage is initialized before configuration. ```dart CachedQuery.instance.configFlutter( storage: await CachedStorage.ensureInitialized(), config: GlobalQueryConfigFlutter(), ); ``` -------------------------------- ### Apply Standard Compilation Settings Source: https://github.com/d-james-gh/cached_query/blob/main/packages/cached_query_flutter/example/linux/CMakeLists.txt Defines a function to apply standard compilation settings to a target, including C++ standard, warning options, optimization levels, and preprocessor definitions. Use with caution as plugins may use this function by default. ```cmake function(APPLY_STANDARD_SETTINGS TARGET) target_compile_features(${TARGET} PUBLIC cxx_std_14) target_compile_options(${TARGET} PRIVATE -Wall -Werror) target_compile_options(${TARGET} PRIVATE "<$>:-O3>") target_compile_definitions(${TARGET} PRIVATE "<$>:NDEBUG>") endfunction() ``` -------------------------------- ### Enable Refetch on Connection Restore Source: https://github.com/d-james-gh/cached_query/blob/main/docs/docs/docs/03-flutter-additions.md Configure Cached Query to automatically refetch active queries when the network connection is restored. This uses the Connectivity Plus package. ```dart CachedQuery.instance.configFlutter( config: GlobalQueryConfigFlutter( refetchOnConnection: true, ), ); ``` -------------------------------- ### Initialize CachedQuery with Observer Source: https://github.com/d-james-gh/cached_query/blob/main/docs/docs/docs/guides/09-observer.md Configure CachedQuery with an observer during initialization. This sets up global observation for all queries and mutations. ```dart void main() async { WidgetsFlutterBinding.ensureInitialized(); CachedQuery.instance.configFlutter( ...config observer: [Observer()], ); runApp(const MyApp()); } ``` -------------------------------- ### Initialize Cached Storage Source: https://github.com/d-james-gh/cached_query/blob/main/docs/docs/docs/04-storage.md Initialize Cached Storage before making any queries. This ensures that query data can be persisted. ```dart void main() async { CachedQuery.instance.configFlutter( storage: await CachedStorage.ensureInitialized(), ); } ```