### Basic CMake Project Setup Source: https://github.com/drdejavung/pocketbase_drift/blob/master/example/linux/CMakeLists.txt Initializes CMake version, sets the project name, and defines the executable binary name. This is a fundamental starting point for any CMake project. ```cmake cmake_minimum_required(VERSION 3.10) project(runner LANGUAGES CXX) # The name of the executable created for the application. Change this to change # the on-disk name of your application. set(BINARY_NAME "example") # The unique GTK application identifier for this application. See: # https://wiki.gnome.org/HowDoI/ChooseApplicationID set(APPLICATION_ID "com.example.example") ``` -------------------------------- ### Start PocketBase Instance Source: https://github.com/drdejavung/pocketbase_drift/blob/master/test/test-instruction.md Run this command in your terminal to start a local PocketBase server. ```bash ./pocketbase serve ``` -------------------------------- ### Install Bundled Libraries Source: https://github.com/drdejavung/pocketbase_drift/blob/master/example/linux/CMakeLists.txt Iterates through a list of bundled libraries and installs each one to the lib directory within the installation bundle. These are also part of the runtime components. ```cmake foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES}) install(FILES "${bundled_library}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) endforeach(bundled_library) ``` -------------------------------- ### Installation Target: Executable Source: https://github.com/drdejavung/pocketbase_drift/blob/master/example/windows/CMakeLists.txt Installs the main application executable to the specified runtime destination. This component is labeled 'Runtime'. ```cmake install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" COMPONENT Runtime) ``` -------------------------------- ### Initialize and Force Install Prefix Source: https://github.com/drdejavung/pocketbase_drift/blob/master/example/linux/CMakeLists.txt Sets the installation prefix to a bundle directory and forces the cache to update. This is part of the default installation procedure, which creates a relocatable bundle in the build directory. ```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() ``` -------------------------------- ### Installation Target: Bundled Plugin Libraries Source: https://github.com/drdejavung/pocketbase_drift/blob/master/example/windows/CMakeLists.txt Installs any bundled plugin libraries to the application bundle. This ensures that all necessary plugin code is available at runtime. ```cmake if(PLUGIN_BUNDLED_LIBRARIES) install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) endif() ``` -------------------------------- ### Installation Target: Flutter Library Source: https://github.com/drdejavung/pocketbase_drift/blob/master/example/windows/CMakeLists.txt Installs the main Flutter library file to the root of the application bundle. This is a core component for Flutter applications. ```cmake install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) ``` -------------------------------- ### Start Local PocketBase Server Source: https://github.com/drdejavung/pocketbase_drift/blob/master/example/README.md The URL to access the locally running PocketBase server. Ensure the server is running before accessing. ```bash http://127.0.0.1:8090 ``` -------------------------------- ### Clean Build Bundle Directory on Install Source: https://github.com/drdejavung/pocketbase_drift/blob/master/example/linux/CMakeLists.txt Ensures the build bundle directory is clean before installation by recursively removing its contents. This is executed as a runtime component during the installation process. ```cmake install( CODE " file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\") " COMPONENT Runtime) ``` -------------------------------- ### Setting Installation Runtime Path Source: https://github.com/drdejavung/pocketbase_drift/blob/master/example/linux/CMakeLists.txt Configures the runtime path for installed libraries relative to the binary. This is crucial for ensuring that dynamically linked libraries can be found at runtime. ```cmake # Load bundled libraries from the lib/ directory relative to the binary. set(CMAKE_INSTALL_RPATH "$ORIGIN/lib") ``` -------------------------------- ### Web Setup for Drift Source: https://github.com/drdejavung/pocketbase_drift/blob/master/README.md For web applications, copy the 'sqlite3.wasm' binary and 'drift_worker.js' file into your project's 'web/' directory. Rename 'drift_worker.js' to 'drift_worker.dart.js'. ```bash 1. Download the latest `sqlite3.wasm` from the [sqlite3.dart releases](https://github.com/simolus3/sqlite3.dart/releases) and the latest `drift_worker.js` from the [drift releases](https://github.com/simolus3/drift/releases). 2. Place each file inside your project's `web/` folder. 3. Rename `drift_worker.js` to `drift_worker.dart.js`. ``` -------------------------------- ### Installation Target: AOT Library Source: https://github.com/drdejavung/pocketbase_drift/blob/master/example/windows/CMakeLists.txt Installs the Ahead-Of-Time (AOT) compiled library for Profile and Release builds. This improves runtime performance by providing pre-compiled code. ```cmake install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" CONFIGURATIONS Profile;Release COMPONENT Runtime) ``` -------------------------------- ### Installation: Flutter Assets Source: https://github.com/drdejavung/pocketbase_drift/blob/master/example/windows/CMakeLists.txt Removes the existing Flutter assets directory and then copies the newly built assets to the application's data directory. This ensures assets are up-to-date. ```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) ``` -------------------------------- ### Install Flutter Assets Source: https://github.com/drdejavung/pocketbase_drift/blob/master/example/linux/CMakeLists.txt Ensures the Flutter assets directory is completely re-copied on each build to prevent stale files from previous installations. This is crucial for maintaining up-to-date assets. ```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) ``` -------------------------------- ### Installation Target: ICU Data Source: https://github.com/drdejavung/pocketbase_drift/blob/master/example/windows/CMakeLists.txt Installs the ICU data file to the data directory within the application bundle. This is essential for internationalization support. ```cmake install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) ``` -------------------------------- ### Install AOT Library Conditionally Source: https://github.com/drdejavung/pocketbase_drift/blob/master/example/linux/CMakeLists.txt Installs the Ahead-Of-Time (AOT) compiled library only on non-Debug builds. This optimizes performance for release versions by using pre-compiled code. ```cmake if(NOT CMAKE_BUILD_TYPE MATCHES "Debug") install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) endif() ``` -------------------------------- ### Cache Custom API GET Requests Source: https://github.com/drdejavung/pocketbase_drift/blob/master/README.md Enable offline availability for custom API routes by using the `send` method with a `RequestPolicy`. Caching is applied by default to GET requests. ```dart // This request will be cached and available offline. try { final customData = await client.send( '/api/my-custom-route', requestPolicy: RequestPolicy.cacheAndNetwork, // Use the desired policy ); } catch (e) { // Handle errors, e.g., if networkOnly fails or cache is empty } ``` -------------------------------- ### Export Flutter library and ICU data Source: https://github.com/drdejavung/pocketbase_drift/blob/master/example/windows/flutter/CMakeLists.txt Exports the Flutter library path and the ICU data file path to the parent scope for use in the installation step. ```cmake set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) ``` ```cmake set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) ``` ```cmake set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) ``` ```cmake set(AOT_LIBRARY "${PROJECT_DIR}/build/windows/app.so" PARENT_SCOPE) ``` -------------------------------- ### Get a Single Record Source: https://github.com/drdejavung/pocketbase_drift/blob/master/README.md Fetch a single record from a collection by its ID. This operation retrieves the record once. ```dart // Get a single record final post = await client.collection('posts').getOne('RECORD_ID'); ``` -------------------------------- ### Retrieve Cached File Bytes Directly Source: https://github.com/drdejavung/pocketbase_drift/blob/master/README.md Get the raw bytes of a file that has been cached for offline use. This allows for direct manipulation or processing of file data. ```dart // Or get the file bytes directly final bytes = await client.files.getFileBytes( recordId: postRecord.id, recordCollectionName: postRecord.collectionName, fileName: postRecord.get('my_image_field'), requestPolicy: RequestPolicy.cacheAndNetwork, ); ``` -------------------------------- ### Initialize PocketBase Drift Client Source: https://github.com/drdejavung/pocketbase_drift/blob/master/README.md Replace the standard PocketBase client with the $PocketBase.database client for offline capabilities. This is a direct replacement for the default client initialization. ```dart - import 'package:pocketbase/pocketbase.dart'; + import 'package:pocketbase_drift/pocketbase_drift.dart'; - final client = PocketBase('http://127.0.0.1:8090'); + final client = $PocketBase.database('http://127.0.0.1:8090'); ``` -------------------------------- ### Set up Reactive Streams with Raw SQL Source: https://github.com/drdejavung/pocketbase_drift/blob/master/README.md Enable reactive updates for raw SQL queries by using the `.watch()` method instead of `.get()`. Ensure you specify the relevant tables in `readsFrom` for reactivity to function correctly. ```dart // Stream that updates when data changes final stream = client.db.customSelect( "SELECT * FROM services WHERE service = 'posts'", readsFrom: {client.db.services}, // Required for reactivity ).watch(); stream.listen((rows) { print('Posts updated: ${rows.length} items'); }); ``` -------------------------------- ### Define plugin wrapper sources Source: https://github.com/drdejavung/pocketbase_drift/blob/master/example/windows/flutter/CMakeLists.txt Lists the C++ source files for the plugin registrar and prepends the wrapper root directory path. ```cmake list(APPEND CPP_WRAPPER_SOURCES_PLUGIN "plugin_registrar.cc" ) list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/") ``` -------------------------------- ### Cross-Building Root Filesystem Configuration Source: https://github.com/drdejavung/pocketbase_drift/blob/master/example/linux/CMakeLists.txt Sets up the root filesystem for cross-building environments. This is used when building for a different architecture or operating system than the host system. ```cmake # Root filesystem for cross-building. 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() ``` -------------------------------- ### Run Flutter Tests Source: https://github.com/drdejavung/pocketbase_drift/blob/master/test/test-instruction.md Execute the Flutter tests for the pocketbase_drift store using this command. ```bash flutter test test/pocketbase_drift_store_test.dart ``` -------------------------------- ### Apply Standard Compiler Settings Source: https://github.com/drdejavung/pocketbase_drift/blob/master/example/linux/CMakeLists.txt Configures C++ standard to C++14, enables all warnings, and sets optimization levels based on the build configuration. Use this for consistent build settings across targets. ```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() ``` -------------------------------- ### Link Dependencies and Include Directories Source: https://github.com/drdejavung/pocketbase_drift/blob/master/example/windows/runner/CMakeLists.txt Links necessary libraries (flutter, flutter_wrapper_app, dwmapi.lib) and adds the source directory to include paths for the runner executable. Add any other application-specific dependencies here. ```cmake target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app) target_link_libraries(${BINARY_NAME} PRIVATE "dwmapi.lib") target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") ``` -------------------------------- ### Apply Standard Build Settings Source: https://github.com/drdejavung/pocketbase_drift/blob/master/example/windows/runner/CMakeLists.txt Applies a standard set of build settings to the executable target. This can be customized for applications requiring different build configurations. ```cmake apply_standard_settings(${BINARY_NAME}) ``` -------------------------------- ### Define application wrapper sources Source: https://github.com/drdejavung/pocketbase_drift/blob/master/example/windows/flutter/CMakeLists.txt Lists the C++ source files for the Flutter engine and view controller, and prepends the wrapper root directory path. ```cmake list(APPEND CPP_WRAPPER_SOURCES_APP "flutter_engine.cc" "flutter_view_controller.cc" ) list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/") ``` -------------------------------- ### Define core wrapper sources Source: https://github.com/drdejavung/pocketbase_drift/blob/master/example/windows/flutter/CMakeLists.txt Lists the core C++ source files for the wrapper and prepends the wrapper root directory path. ```cmake list(APPEND CPP_WRAPPER_SOURCES_CORE "core_implementations.cc" "standard_codec.cc" ) list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/") ``` -------------------------------- ### Define wrapper root directory Source: https://github.com/drdejavung/pocketbase_drift/blob/master/example/windows/flutter/CMakeLists.txt Sets the root directory for the C++ client wrapper files. ```cmake set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper") ``` -------------------------------- ### Find and Check PkgConfig Modules Source: https://github.com/drdejavung/pocketbase_drift/blob/master/example/linux/flutter/CMakeLists.txt Uses PkgConfig to find and check for required GTK, GLIB, and GIO modules. These are essential system-level dependencies for Flutter Linux applications. ```cmake 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) ``` -------------------------------- ### Initialize Client with Custom Cache TTL Source: https://github.com/drdejavung/pocketbase_drift/blob/master/README.md Configure the cache expiration time-to-live (TTL) when initializing the PocketBase client. Set a custom duration or disable automatic cleanup by setting TTL to null. ```dart final client = $PocketBase.database( 'https://example.pocketbase.io', cacheTtl: Duration(days: 30), // Custom TTL: 30 days ); // Or disable automatic cleanup (keep data forever) final clientNoExpiry = $PocketBase.database( 'https://example.pocketbase.io', cacheTtl: null, ); ``` -------------------------------- ### Set Runtime Output Directory Source: https://github.com/drdejavung/pocketbase_drift/blob/master/example/linux/CMakeLists.txt Configures the runtime output directory for the main binary to a specific subdirectory within the build directory. This ensures that resources remain in their correct relative locations and prevents accidental execution of unbundled copies. ```cmake set_target_properties(${BINARY_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/intermediates_do_not_run" ) ``` -------------------------------- ### Create static plugin wrapper library Source: https://github.com/drdejavung/pocketbase_drift/blob/master/example/windows/flutter/CMakeLists.txt Creates a static library target for the Flutter plugin wrapper, including core and plugin-specific sources. It sets properties for position-independent code and visibility, links against the Flutter library, and specifies include directories. ```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) ``` -------------------------------- ### Use Built-in Query Builder for Simplified Queries Source: https://github.com/drdejavung/pocketbase_drift/blob/master/README.md Leverage the `$query` method for simpler database queries. It internally handles PocketBase-style filter syntax and automatic JSON extraction, simplifying common data retrieval tasks. ```dart // Uses PocketBase-style filter syntax internally final posts = await client.db.$query( 'posts', filter: "published = true && author != ''", sort: '-created', limit: 10, ).get(); ``` -------------------------------- ### Set Admin Credentials Source: https://github.com/drdejavung/pocketbase_drift/blob/master/example/README.md Define the username and password for the PocketBase admin user. Ensure these are kept secure. ```dart const username = 'test@admin.com'; const password = 'Password123'; ``` -------------------------------- ### Define Application Executable Source: https://github.com/drdejavung/pocketbase_drift/blob/master/example/linux/CMakeLists.txt Defines the main executable target for the application, listing all necessary source files. Ensure all application source files are included here. ```cmake add_executable(${BINARY_NAME} "main.cc" "my_application.cc" "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" ) ``` -------------------------------- ### Create static application wrapper library Source: https://github.com/drdejavung/pocketbase_drift/blob/master/example/windows/flutter/CMakeLists.txt Creates a static library target for the Flutter application runner wrapper, including core and application-specific sources. It links against the Flutter library and specifies include directories. ```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) ``` -------------------------------- ### Project and Minimum CMake Version Source: https://github.com/drdejavung/pocketbase_drift/blob/master/example/windows/CMakeLists.txt Sets the minimum required CMake version and the project name. Ensures compatibility with specified CMake versions. ```cmake cmake_minimum_required(VERSION 3.14) project(example LANGUAGES CXX) ``` -------------------------------- ### Configure AuthStore with SharedPreferences Source: https://github.com/drdejavung/pocketbase_drift/blob/master/README.md Instantiate a custom AuthStore that preserves authentication data across app sessions, even after logout. Set `clearOnLogout` to `false` to enable this behavior. ```dart final prefs = await SharedPreferences.getInstance(); // Create auth store that preserves data on logout final authStore = $AuthStore.prefs( prefs, 'pb_auth', clearOnLogout: false, // Default is true ); final client = $PocketBase.database( 'https://example.pocketbase.io', authStore: authStore, ); ``` -------------------------------- ### Apply Standard Compilation Settings Source: https://github.com/drdejavung/pocketbase_drift/blob/master/example/windows/CMakeLists.txt A function to apply common compilation settings to a target. Includes C++ standard, warning levels, exception handling, and debug definitions. ```cmake function(APPLY_STANDARD_SETTINGS TARGET) target_compile_features(${TARGET} PUBLIC cxx_std_17) target_compile_options(${TARGET} PRIVATE /W4 /WX /wd"4100") target_compile_options(${TARGET} PRIVATE /EHsc) target_compile_definitions(${TARGET} PRIVATE "_HAS_EXCEPTIONS=0") target_compile_definitions(${TARGET} PRIVATE "$:_DEBUG") endfunction() ``` -------------------------------- ### Create Flutter interface library Source: https://github.com/drdejavung/pocketbase_drift/blob/master/example/windows/flutter/CMakeLists.txt Creates an INTERFACE library target for Flutter, specifying include directories and linking against the Flutter library. ```cmake add_library(flutter INTERFACE) target_include_directories(flutter INTERFACE "${EPHEMERAL_DIR}" ) target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib") add_dependencies(flutter flutter_assemble) ``` -------------------------------- ### Custom Command for Flutter Tool Backend Source: https://github.com/drdejavung/pocketbase_drift/blob/master/example/linux/flutter/CMakeLists.txt A custom command to execute the Flutter tool backend script. It uses a phony output file to ensure it runs on every build, as precise input/output tracking is not yet supported. ```cmake add_custom_command( OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} ${CMAKE_CURRENT_BINARY_DIR}/_phony_ COMMAND ${CMAKE_COMMAND} -E env ${FLUTTER_TOOL_ENVIRONMENT} "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.sh" ${FLUTTER_TARGET_PLATFORM} ${CMAKE_BUILD_TYPE} VERBATIM ) ``` -------------------------------- ### Include generated configuration Source: https://github.com/drdejavung/pocketbase_drift/blob/master/example/windows/flutter/CMakeLists.txt Includes the generated configuration file provided by the Flutter tool. This file contains essential build settings. ```cmake include(${EPHEMERAL_DIR}/generated_config.cmake) ``` -------------------------------- ### Define Flutter library headers Source: https://github.com/drdejavung/pocketbase_drift/blob/master/example/windows/flutter/CMakeLists.txt Lists the header files for the Flutter library and prepends the ephemeral directory path to each. ```cmake list(APPEND FLUTTER_LIBRARY_HEADERS "flutter_export.h" "flutter_windows.h" "flutter_messenger.h" "flutter_plugin_registrar.h" "flutter_texture_registrar.h" ) ``` ```cmake list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/") ``` -------------------------------- ### Link Application Dependencies Source: https://github.com/drdejavung/pocketbase_drift/blob/master/example/linux/CMakeLists.txt Links the application target with necessary libraries, including the Flutter engine and GTK. Add any other application-specific libraries here. ```cmake target_link_libraries(${BINARY_NAME} PRIVATE flutter) target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK) ``` -------------------------------- ### Include Generated Plugins Source: https://github.com/drdejavung/pocketbase_drift/blob/master/example/windows/CMakeLists.txt Includes the CMake script for generated plugins. This manages the building and integration of project plugins into the application. ```cmake include(flutter/generated_plugins.cmake) ``` -------------------------------- ### General Compilation Settings Source: https://github.com/drdejavung/pocketbase_drift/blob/master/example/linux/CMakeLists.txt Applies compilation settings to most targets. New options should generally be added to specific targets rather than here to avoid conflicts with plugins. ```cmake # Compilation settings that should be applied to most targets. # # Be cautious about adding new options here, as plugins use this function by # default. In most cases, you should add new options to specific targets instead ``` -------------------------------- ### Define Flutter library path Source: https://github.com/drdejavung/pocketbase_drift/blob/master/example/windows/flutter/CMakeLists.txt Specifies the path to the Flutter Windows DLL. ```cmake set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll") ``` -------------------------------- ### Unicode Support Source: https://github.com/drdejavung/pocketbase_drift/blob/master/example/windows/CMakeLists.txt Enables Unicode support for all projects by defining specific preprocessor macros. This ensures proper handling of Unicode characters in the application. ```cmake add_definitions(-DUNICODE -D_UNICODE) ``` -------------------------------- ### Join Data Across Collections with Raw SQL Source: https://github.com/drdejavung/pocketbase_drift/blob/master/README.md Perform SQL joins across different PocketBase collections by referencing them as rows in the generic 'services' table. Use `json_extract` to access fields within the 'data' JSON column. ```dart final results = await client.db.customSelect(''' SELECT p.id as post_id, json_extract(p.data, '\$.title') as post_title, json_extract(u.data, '\$.name') as author_name FROM services p JOIN services u ON json_extract(p.data, '\$.author') = u.id AND u.service = 'users' WHERE p.service = 'posts' ''').get(); ``` -------------------------------- ### Executable Name Configuration Source: https://github.com/drdejavung/pocketbase_drift/blob/master/example/windows/CMakeLists.txt Defines the name of the application's executable. This variable controls the on-disk name of the built application. ```cmake set(BINARY_NAME "example") ``` -------------------------------- ### Set Database Schema for Offline Records Source: https://github.com/drdejavung/pocketbase_drift/blob/master/README.md Provide the database schema to the client by loading 'pb_schema.json' from assets. This enables offline caching by allowing the local database to understand collection structures. ```dart // 1. Load the schema from your assets final schema = await rootBundle.loadString('assets/pb_schema.json'); // 2. Initialize the client and set the schema final client = $PocketBase.database('http://127.0.0.1:8090') ..setSchema(schema); ``` -------------------------------- ### Add PocketBase Drift Dependency Source: https://github.com/drdejavung/pocketbase_drift/blob/master/README.md Add the pocketbase_drift package to your pubspec.yaml file. Ensure you use the latest version available. ```yaml dependencies: pocketbase_drift: ^0.4.3 # Use the latest version ``` -------------------------------- ### Modern CMake Policy Source: https://github.com/drdejavung/pocketbase_drift/blob/master/example/windows/CMakeLists.txt Explicitly opts into modern CMake behaviors to avoid warnings in recent CMake versions. Ensures consistent behavior across different CMake releases. ```cmake cmake_policy(SET CMP0063 NEW) ``` -------------------------------- ### Set Global Request Policy Source: https://github.com/drdejavung/pocketbase_drift/blob/master/README.md Configure a default request policy for all subsequent database operations on the client. This policy can be overridden on a per-call basis. ```dart final client = $PocketBase.database( 'http://127.0.0.1:8090', requestPolicy: RequestPolicy.networkFirst, ); // All methods will now default to networkFirst await client.collection('posts').getFullList(); // Uses networkFirst await client.collection('posts').create(body: {...}); // Uses networkFirst ``` -------------------------------- ### Execute Raw SQL Query for Data Retrieval Source: https://github.com/drdejavung/pocketbase_drift/blob/master/README.md Use `customSelect` to execute raw SQL queries against the database. This is useful for complex queries, custom joins, or when needing to extract specific JSON data from the 'data' column. ```dart // Simple query - get all posts final results = await client.db.customSelect( "SELECT * FROM services WHERE service = 'posts'", ).get(); ``` ```dart // Query with JSON extraction final posts = await client.db.customSelect(''' SELECT id, json_extract(data, '\$.title') as title, json_extract(data, '\$.author') as author, created FROM services WHERE service = 'posts' AND json_extract(data, '\$.published') = 1 ORDER BY created DESC LIMIT 10 ''').get(); // Access results for (final row in posts) { print('${row.read('title')} by ${row.read('author')}'); } ``` -------------------------------- ### Add Runner Subdirectory Source: https://github.com/drdejavung/pocketbase_drift/blob/master/example/windows/CMakeLists.txt Includes the runner subdirectory for application build rules. This typically contains the main entry point and platform-specific configurations. ```cmake add_subdirectory("runner") ``` -------------------------------- ### Add Version Preprocessor Definitions Source: https://github.com/drdejavung/pocketbase_drift/blob/master/example/windows/runner/CMakeLists.txt Adds preprocessor definitions to the build configuration to embed Flutter version information directly into the compiled executable. This allows runtime access to version details. ```cmake target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION=\"${FLUTTER_VERSION}\"") target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MAJOR=${FLUTTER_VERSION_MAJOR}") target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MINOR=${FLUTTER_VERSION_MINOR}") target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_PATCH=${FLUTTER_VERSION_PATCH}") target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_BUILD=${FLUTTER_VERSION_BUILD}") ``` -------------------------------- ### Build Configuration Types Source: https://github.com/drdejavung/pocketbase_drift/blob/master/example/windows/CMakeLists.txt Configures the available build types (Debug, Profile, Release) for multi-configuration generators. For single-configuration generators, it sets the default build type if not already specified. ```cmake get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) if(IS_MULTICONFIG) set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release" CACHE STRING "" FORCE) else() if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) set(CMAKE_BUILD_TYPE "Debug" CACHE STRING "Flutter build mode" FORCE) set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS "Debug" "Profile" "Release") endif() endif() ``` -------------------------------- ### Add Flutter Subdirectory Source: https://github.com/drdejavung/pocketbase_drift/blob/master/example/windows/CMakeLists.txt Includes the Flutter managed directory as a subdirectory. This is necessary for building Flutter-specific components. ```cmake set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") add_subdirectory(${FLUTTER_MANAGED_DIR}) ``` -------------------------------- ### Fetch Records with Sorting and Policy Source: https://github.com/drdejavung/pocketbase_drift/blob/master/README.md Retrieve a one-time list of records from a collection, sorted by a specified field and using a defined request policy. ```dart // Get a one-time list of posts, sorted by creation date final posts = await client.collection('posts').getFullList( sort: '-created', requestPolicy: RequestPolicy.cacheAndNetwork, // Explicitly set policy ); ``` -------------------------------- ### Create a New Record (Online/Offline) Source: https://github.com/drdejavung/pocketbase_drift/blob/master/README.md Create a new record in a collection, with automatic handling for offline scenarios. The operation is applied locally and synced later if offline. ```dart // Create a new record (works online and offline) final newRecord = await client.collection('posts').create( body: { 'title': 'My Offline Post', 'content': 'This was created without a connection.', }, requestPolicy: RequestPolicy.cacheAndNetwork, ); ``` -------------------------------- ### Display Cached Images with PocketBaseImageProvider Source: https://github.com/drdejavung/pocketbase_drift/blob/master/README.md Utilize PocketBaseImageProvider for seamless display of images that are automatically cached for offline access. This simplifies image handling in your UI. ```dart // Use the included PocketBaseImageProvider for easy display Image( image: PocketBaseImageProvider( client: client, recordId: postRecord.id, recordCollectionName: postRecord.collectionName, filename: postRecord.get('my_image_field'), // The filename ), ); ``` -------------------------------- ### Profile Build Mode Linker Flags Source: https://github.com/drdejavung/pocketbase_drift/blob/master/example/windows/CMakeLists.txt Sets linker flags for the Profile build mode to match those of the Release build mode. Ensures consistent linking behavior for performance-oriented builds. ```cmake set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}") set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}") set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}") set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}") ``` -------------------------------- ### Define Executable Target Source: https://github.com/drdejavung/pocketbase_drift/blob/master/example/windows/runner/CMakeLists.txt Defines the main executable target for the runner application, listing all necessary source files and resources. Ensure BINARY_NAME is consistent with the top-level CMakeLists.txt for `flutter run` compatibility. ```cmake cmake_minimum_required(VERSION 3.14) project(runner LANGUAGES CXX) add_executable(${BINARY_NAME} WIN32 "flutter_window.cpp" "main.cpp" "utils.cpp" "win32_window.cpp" "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" "Runner.rc" "runner.exe.manifest" ) ``` -------------------------------- ### Defining Build Configuration Type Source: https://github.com/drdejavung/pocketbase_drift/blob/master/example/linux/CMakeLists.txt Sets the default build type (Debug, Profile, Release) if not already defined. This influences compiler optimizations and debugging information. ```cmake # Define build configuration options. if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) set(CMAKE_BUILD_TYPE "Debug" CACHE STRING "Flutter build mode" FORCE) set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS "Debug" "Profile" "Release") endif() ``` -------------------------------- ### Fetch Multi Relation with Expansion Source: https://github.com/drdejavung/pocketbase_drift/blob/master/README.md Retrieve a record and expand its multi-relation field, returning a list of related records that can be accessed by index or iterated. ```dart // Fetch a post with multiple tags expanded final post = await client.collection('posts').getOne( 'RECORD_ID', expand: 'tags', ); // Access by index final firstTag = post.get('expand.tags.0.name'); final secondTag = post.get('expand.tags.1.name'); // Or get all as a list and iterate final tags = post.get>('expand.tags'); for (final tag in tags) { print(tag.get('name')); } ``` -------------------------------- ### Execute Multiple Operations in a Single Transaction Source: https://github.com/drdejavung/pocketbase_drift/blob/master/README.md Use batch requests to perform multiple create, update, delete, or upsert operations atomically in one HTTP request. This improves efficiency and ensures data consistency. ```dart // Create a batch instance final batch = client.$createBatch(); // Queue operations across multiple collections batch.collection('posts').create(body: { 'title': 'New Post', 'content': 'Created in a batch', }); batch.collection('posts').update('abc123', body: { 'title': 'Updated Title', }); batch.collection('comments').delete('def456'); // Upsert: creates if ID doesn't exist, updates if it does batch.collection('tags').upsert(body: { 'id': 'tag_flutter', 'name': 'Flutter', }); // Send all operations in a single request final results = await batch.send( requestPolicy: RequestPolicy.cacheAndNetwork, ); // Check results for (final result in results) { if (result.isSuccess) { print('${result.collection}: Success'); final record = result.record; // Access the returned RecordModel } else { print('${result.collection}: Failed with status ${result.status}'); } } ``` -------------------------------- ### Override Global Request Policy Source: https://github.com/drdejavung/pocketbase_drift/blob/master/README.md Demonstrates how to override the globally set request policy for a specific method call, allowing for granular control over data fetching behavior. ```dart await client.collection('posts').getFullList( requestPolicy: RequestPolicy.cacheOnly, // Overrides global default ); ``` -------------------------------- ### Configure Flutter Library Interface Source: https://github.com/drdejavung/pocketbase_drift/blob/master/example/linux/flutter/CMakeLists.txt Defines an INTERFACE library for Flutter, specifying include directories and linking against system libraries and the Flutter shared object. This allows other targets to easily depend on Flutter. ```cmake add_library(flutter INTERFACE) target_include_directories(flutter INTERFACE "${EPHEMERAL_DIR}" ) target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}") target_link_libraries(flutter INTERFACE PkgConfig::GTK PkgConfig::GLIB PkgConfig::GIO ) ``` -------------------------------- ### Set ephemeral directory Source: https://github.com/drdejavung/pocketbase_drift/blob/master/example/windows/flutter/CMakeLists.txt Sets the directory for ephemeral build files, which is typically generated by the Flutter tool. ```cmake set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") ``` -------------------------------- ### Execute Raw SQL Statements for Data Modification Source: https://github.com/drdejavung/pocketbase_drift/blob/master/README.md Use `customStatement` to execute raw SQL commands for data manipulation operations such as INSERT, UPDATE, or DELETE. This method is suitable for statements that do not return data. ```dart await client.db.customStatement( "DELETE FROM services WHERE service = 'temp_data'", ); ``` -------------------------------- ### Add Flutter Assemble Dependency Source: https://github.com/drdejavung/pocketbase_drift/blob/master/example/windows/runner/CMakeLists.txt Ensures that the Flutter tool's assembly process is completed before the runner executable is built. This is a mandatory step for Flutter applications. ```cmake add_dependencies(${BINARY_NAME} flutter_assemble) ``` -------------------------------- ### Define List Prepend Function Source: https://github.com/drdejavung/pocketbase_drift/blob/master/example/linux/flutter/CMakeLists.txt A custom function to prepend elements to a list, as `list(TRANSFORM ... PREPEND ...)` is not available in CMake version 3.10. ```cmake function(list_prepend LIST_NAME PREFIX) set(NEW_LIST "") foreach(element ${${LIST_NAME}}) list(APPEND NEW_LIST "${PREFIX}${element}") endforeach(element) set(${LIST_NAME} "${NEW_LIST}" PARENT_SCOPE) endfunction() ``` -------------------------------- ### Flutter Web Service Worker Initialization Source: https://github.com/drdejavung/pocketbase_drift/blob/master/example/web/index.html This snippet shows the JavaScript code used to initialize the service worker for a Flutter web application. It's responsible for loading the main Dart entry point and initializing the Flutter engine. ```javascript var serviceWorkerVersion = null; window.addEventListener('load', function(ev) { // Download main.dart.js _flutter.loader.loadEntrypoint({ serviceWorker: { serviceWorkerVersion: serviceWorkerVersion, }, onEntrypointLoaded: function(engineInitializer) { engineInitializer.initializeEngine().then(function(appRunner) { appRunner.runApp(); }); } }); }); ``` -------------------------------- ### Assemble Flutter Target Source: https://github.com/drdejavung/pocketbase_drift/blob/master/example/linux/flutter/CMakeLists.txt Defines a custom target 'flutter_assemble' that depends on the Flutter library and its headers. This target ensures that the Flutter tool backend command is executed. ```cmake add_custom_target(flutter_assemble DEPENDS "${FLUTTER_LIBRARY}" ${FLUTTER_LIBRARY_HEADERS} ) ``` -------------------------------- ### Fetch Reactive Stream of Records Source: https://github.com/drdejavung/pocketbase_drift/blob/master/README.md Obtain a reactive stream that emits updates for all records in a collection. This is useful for real-time UI updates. ```dart // Get a reactive stream of all "posts" final stream = client.collection('posts').watchRecords(); ``` -------------------------------- ### Perform Local Full-Text Search Source: https://github.com/drdejavung/pocketbase_drift/blob/master/README.md Search for text within fields of a specific collection or across all collections locally. This enables quick data retrieval without server interaction. ```dart // Search all fields in the 'posts' collection for the word "flutter" final results = await client.collection('posts').search('flutter').get(); // Search across all collections final globalResults = await client.search('flutter').get(); ``` -------------------------------- ### Fetch Nested Multi-Level Expansion Source: https://github.com/drdejavung/pocketbase_drift/blob/master/README.md Retrieve a record with deeply nested relations expanded, enabling access to data several levels down the relationship chain. ```dart // Expand nested relations: post -> author -> profile (all single relations) final post = await client.collection('posts').getOne( 'RECORD_ID', expand: 'author.profile', ); // Access deeply nested fields (no index for single relations) final bio = post.get('expand.author.expand.profile.bio'); final avatar = post.get('expand.author.expand.profile.avatar'); ``` -------------------------------- ### Run Cache Maintenance to Clean Expired Data Source: https://github.com/drdejavung/pocketbase_drift/blob/master/README.md Manually trigger the cleanup of expired cached data by calling `runMaintenance()`. This can be done on app startup or periodically to manage local storage. ```dart // Run maintenance with the configured TTL final result = await client.runMaintenance(); print('Cleaned up ${result.totalDeleted} expired items'); // Or run with a one-time custom TTL await client.runMaintenance(ttl: Duration(days: 7)); ``` -------------------------------- ### Flutter assemble custom target Source: https://github.com/drdejavung/pocketbase_drift/blob/master/example/windows/flutter/CMakeLists.txt Creates a custom target named 'flutter_assemble' that depends on the Flutter library, its headers, and all wrapper source files. This target ensures these components are built when needed. ```cmake add_custom_target(flutter_assemble DEPENDS "${FLUTTER_LIBRARY}" ${FLUTTER_LIBRARY_HEADERS} ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} ${CPP_WRAPPER_SOURCES_APP} ) ``` -------------------------------- ### Watch Records with Network Fetching State Source: https://github.com/drdejavung/pocketbase_drift/blob/master/README.md Monitor records along with their network fetching state, which is useful for managing loading indicators in the UI and preventing visual glitches. ```dart // Watch records with network fetching state (useful to avoid UI flashing) final stateStream = client.collection('posts').watchRecordsState( requestPolicy: RequestPolicy.cacheAndNetwork, ); stateStream.listen((state) { if (state.data.isEmpty && state.isFetchingNetwork) { print('Cache is empty, but we are fetching from the network... show a loading spinner!'); } else { print('Data loaded: ${state.data.length} posts'); } }); ``` -------------------------------- ### Watch a Single Record Source: https://github.com/drdejavung/pocketbase_drift/blob/master/README.md Subscribe to real-time updates for a specific record within a collection. This is ideal for displaying details of a single item. ```dart // Watch a single record final postStream = client.collection('posts').watchRecord('RECORD_ID'); ``` -------------------------------- ### Fetch Single Relation with Expansion Source: https://github.com/drdejavung/pocketbase_drift/blob/master/README.md Retrieve a record and expand its single relation field, allowing direct access to the related record's data. ```dart // Fetch a post with its author expanded (single relation) final post = await client.collection('posts').getOne( 'RECORD_ID', expand: 'author', ); // Access expanded data directly (no index needed) final authorName = post.get('expand.author.name'); final authorEmail = post.get('expand.author.email', 'N/A'); // With default // Get the expanded record as a RecordModel final author = post.get('expand.author'); print(author.get('name')); ``` -------------------------------- ### Bypass Cache for Custom API POST Requests Source: https://github.com/drdejavung/pocketbase_drift/blob/master/README.md Ensure that state-changing requests like POST are sent directly to the network, bypassing any caching mechanisms to prevent unintended side effects. ```dart // This POST request will bypass the cache and go directly to the network. await client.send( '/api/submit-form', method: 'POST', body: {'name': 'test'}, // No requestPolicy needed, but even if provided, it would be ignored. ); ``` -------------------------------- ### Disable Conflicting Windows Macros Source: https://github.com/drdejavung/pocketbase_drift/blob/master/example/windows/runner/CMakeLists.txt Disables Windows-specific macros (NOMINMAX) that might conflict with standard C++ library functions, preventing potential compilation errors. ```cmake target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX") ``` -------------------------------- ### Update an Existing Record Source: https://github.com/drdejavung/pocketbase_drift/blob/master/README.md Modify an existing record in a collection with new data. This operation also supports offline capabilities. ```dart // Update a record await client.collection('posts').update(newRecord.id, body: { 'content': 'The content has been updated.', }); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.