### Run Example (Bash) Source: https://github.com/dickermoshe/convex-dart/blob/master/example/readme.md Executes the Flutter example application after dependencies are installed and the Dart client is generated. This command starts the Flutter app that interacts with the Convex backend. ```bash flutter run ``` -------------------------------- ### Install Dependencies (Bash) Source: https://github.com/dickermoshe/convex-dart/blob/master/example/readme.md Installs necessary dependencies for both the Convex backend (Node.js) and the Dart/Flutter client. Ensures all project components are ready for development and testing. ```bash npm install flutter pub get ``` -------------------------------- ### Run Tests (Bash) Source: https://github.com/dickermoshe/convex-dart/blob/master/example/readme.md Sets up and runs integration tests for the convex-dart project. This involves installing dependencies, generating the Dart client, and then executing the test suite. ```bash npm install flutter pub get convex_dart_cli generate --public-serialize flutter test integration_test/test_all.dart ``` -------------------------------- ### Install convex_dart_cli via command line Source: https://github.com/dickermoshe/convex-dart/blob/master/convex_dart_cli/README.md Demonstrates the command-line instruction to add the convex_dart_cli package as a development dependency using Dart's pub command. ```bash dart pub add dev:convex_dart_cli ``` -------------------------------- ### Windows Installation Configuration Source: https://github.com/dickermoshe/convex-dart/blob/master/example/windows/CMakeLists.txt Configures installation rules for Windows, ensuring that support files are placed alongside the executable for in-place execution. It sets the install prefix and defines directories for data and libraries. ```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}") ``` -------------------------------- ### Installation Bundle Configuration Source: https://github.com/dickermoshe/convex-dart/blob/master/example/linux/CMakeLists.txt Sets up the installation process to create a relocatable bundle in the build directory. It ensures a clean bundle directory on each installation and defines destinations for data and libraries. ```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() install(CODE " file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\") " COMPONENT Runtime) set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib") ``` -------------------------------- ### Connect and Subscribe to Convex Data in Rust Source: https://github.com/dickermoshe/convex-dart/blob/master/convex_dart/rust/README.md Example demonstrating how to initialize the Convex client with a deployment URL, establish a subscription to a data source (e.g., 'getCounter'), and process incoming updates. This showcases real-time data handling. ```rust let mut client = ConvexClient::new(DEPLOYMENT_URL).await?; let mut subscription = client.subscribe("getCounter", vec![]).await?; while let Some(new_val) = subscription.next().await { println!("Counter updated to {new_val:?}"); } ``` -------------------------------- ### GitHub Action to Precompile and Upload Binaries Source: https://github.com/dickermoshe/convex-dart/blob/master/convex_dart/cargokit/docs/precompiled_binaries.md An example GitHub Actions workflow that automates the precompilation and uploading of Rust binaries as GitHub releases. It supports multiple operating systems and includes steps for Android builds. ```yaml on: push: branches: [ main ] name: Precompile Binaries jobs: Precompile: runs-on: ${{ matrix.os }} strategy: fail-fast: false matrix: os: - ubuntu-latest - macOS-latest - windows-latest steps: - uses: actions/checkout@v2 - uses: dart-lang/setup-dart@v1 - name: Install GTK if: (matrix.os == 'ubuntu-latest') run: sudo apt-get update && sudo apt-get install libgtk-3-dev - name: Precompile if: (matrix.os == 'macOS-latest') || (matrix.os == 'windows-latest') run: dart run build_tool precompile-binaries -v --manifest-dir=../../rust --repository=superlistapp/super_native_extensions working-directory: super_native_extensions/cargokit/build_tool env: GITHUB_TOKEN: ${{ secrets.RELEASE_GITHUB_TOKEN }} PRIVATE_KEY: ${{ secrets.RELEASE_PRIVATE_KEY }} - name: Precompile (with Android) if: (matrix.os == 'ubuntu-latest') run: dart run build_tool precompile-binaries -v --manifest-dir=../../rust --repository=superlistapp/super_native_extensions --android-sdk-location=/usr/local/lib/android/sdk --android-ndk-version=24.0.8215888 --android-min-sdk-version=23 working-directory: super_native_extensions/cargokit/build_tool env: GITHUB_TOKEN: ${{ secrets.RELEASE_GITHUB_TOKEN }} PRIVATE_KEY: ${{ secrets.RELEASE_PRIVATE_KEY }} ``` -------------------------------- ### Target and Asset Installation Rules Source: https://github.com/dickermoshe/convex-dart/blob/master/example/windows/CMakeLists.txt Defines rules for installing the main executable, ICU data file, Flutter library, bundled plugin libraries, and native assets. These components are installed to specific directories under the application bundle for runtime access. ```cmake install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" COMPONENT Runtime) install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) if(PLUGIN_BUNDLED_LIBRARIES) install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) endif() set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/windows/") install(DIRECTORY "${NATIVE_ASSETS_DIR}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) ``` -------------------------------- ### Basic CMake Project Setup Source: https://github.com/dickermoshe/convex-dart/blob/master/example/linux/CMakeLists.txt Initializes CMake version, defines the project name and supported languages. Sets executable and application IDs. Ensures modern CMake behavior and configures runtime library paths. ```cmake cmake_minimum_required(VERSION 3.13) project(runner LANGUAGES CXX) set(BINARY_NAME "api") set(APPLICATION_ID "com.example.api") cmake_policy(SET CMP0063 NEW) set(CMAKE_INSTALL_RPATH "$ORIGIN/lib") ``` -------------------------------- ### Install Application Targets and Files Source: https://github.com/dickermoshe/convex-dart/blob/master/example/linux/CMakeLists.txt Installs the main application binary, ICU data file, Flutter library, and bundled plugin libraries to the specified destinations within the installation bundle. ```cmake install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" COMPONENT Runtime) install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES}) install(FILES "${bundled_library}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) endforeach(bundled_library) ``` -------------------------------- ### AOT Library Installation Source: https://github.com/dickermoshe/convex-dart/blob/master/example/windows/CMakeLists.txt Installs the Ahead-Of-Time (AOT) compiled library only for 'Profile' and 'Release' build configurations. This optimizes application startup time and performance for non-debug builds. ```cmake install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" CONFIGURATIONS Profile;Release COMPONENT Runtime) ``` -------------------------------- ### Generate Dart Client (Bash) Source: https://github.com/dickermoshe/convex-dart/blob/master/example/readme.md Generates type-safe Dart client code from Convex functions using the convex_dart_cli. The --public-serialize flag is used for generating serialization logic. ```bash dart run convex_dart_cli generate --public-serialize ``` -------------------------------- ### Install Flutter Assets Source: https://github.com/dickermoshe/convex-dart/blob/master/example/linux/CMakeLists.txt Installs Flutter assets into the bundle's data directory. It first removes any existing assets to ensure a clean copy from the build directory. ```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) ``` -------------------------------- ### Convex Dart CLI: Generating Client Code Source: https://github.com/dickermoshe/convex-dart/blob/master/convex_dart/README.md Provides examples of using the `convex_dart_cli` tool to generate Dart client code from Convex functions. It covers basic usage, specifying custom paths for the Convex project and output directory, and running in production mode. ```bash # Generate and watch for changes (basic usage) convex_dart_cli generate # Specify custom paths convex_dart_cli generate --js ./my-convex-project --output ./lib/src/api # Production mode convex_dart_cli generate --prod ``` -------------------------------- ### Install Convex Rust Client Dependency Source: https://github.com/dickermoshe/convex-dart/blob/master/convex_dart/rust/README.md Add the Convex Rust client as a dependency to your project by including it in your Cargo.toml file. This allows you to use the client's functionalities in your Rust application. ```toml [dependencies] convex = "*" ``` -------------------------------- ### Install AOT Library for Non-Debug Builds Source: https://github.com/dickermoshe/convex-dart/blob/master/example/linux/CMakeLists.txt Conditionally installs the Ahead-Of-Time (AOT) compiled library to the bundle's library directory. This installation only occurs when the build type is not 'Debug'. ```cmake if(NOT CMAKE_BUILD_TYPE MATCHES "Debug") install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) endif() ``` -------------------------------- ### Generate Type-Safe Dart Client with convex_dart_cli Source: https://context7.com/dickermoshe/convex-dart/llms.txt Instructions for installing and using the `convex_dart_cli` tool to generate type-safe Dart clients from your Convex backend functions. Covers basic usage, watching for changes, custom path configuration, production builds, and using alternative JavaScript package managers. ```bash # Install the CLI flutter pub add dev:convex_dart_cli convex_dart # Basic usage - watch mode (development) dart run convex_dart_cli generate # Specify custom paths dart run convex_dart_cli generate --js ./my-convex-project --output ./lib/src/api # Production mode - generate once without watching dart run convex_dart_cli generate --prod # Use different package manager dart run convex_dart_cli generate --js-package-manager bun dart run convex_dart_cli generate --js-package-manager pnpm # Pass additional arguments to convex commands dart run convex_dart_cli generate --convex-dev-args "--typecheck=disable" dart run convex_dart_cli generate --convex-spec-args "--format json" # Press 'r' during watch mode to force regeneration ``` -------------------------------- ### Install convex_dart and convex_dart_cli Source: https://github.com/dickermoshe/convex-dart/blob/master/convex_dart/README.md This snippet shows how to add the convex_dart and convex_dart_cli packages to your Flutter project's dependencies using either the pubspec.yaml file or the command line. ```yaml dependencies: convex_dart: ^latest_version dev_dependencies: convex_dart_cli: ^latest_version ``` ```bash flutter pub add dev:convex_dart_cli convex_dart ``` -------------------------------- ### Install Native Assets Source: https://github.com/dickermoshe/convex-dart/blob/master/example/linux/CMakeLists.txt Installs native assets provided by packages into the bundle's library directory. It ensures that all native assets are copied from the specified source directory. ```cmake set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/linux/") install(DIRECTORY "${NATIVE_ASSETS_DIR}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) ``` -------------------------------- ### Enable Debug Logging with Tracing Subscriber in Rust Source: https://github.com/dickermoshe/convex-dart/blob/master/convex_dart/rust/README.md Configuration for enabling debug logging in the Convex Rust client using the `tracing` crate. This example shows how to initialize `tracing_subscriber` to capture logs, including specific Convex backend logs, by setting the RUST_LOG environment variable. ```rust tracing_subscriber::fmt() .with_env_filter(tracing_subscriber::EnvFilter::from_default_env()) .init(); ``` -------------------------------- ### CMake Project Setup and CargoKit Integration Source: https://github.com/dickermoshe/convex-dart/blob/master/convex_dart/windows/CMakeLists.txt This snippet sets the minimum required CMake version, defines the project name, and includes the CargoKit for integrating Rust code into the C++ project. It uses `apply_cargokit` to manage the Rust build process. ```cmake cmake_minimum_required(VERSION 3.14) # Project-level configuration. set(PROJECT_NAME "convex_dart") project(${PROJECT_NAME} LANGUAGES CXX) include("../cargokit/cmake/cargokit.cmake") apply_cargokit(${PROJECT_NAME} ../rust convex_dart "") ``` -------------------------------- ### Manage Authentication Token in Dart Source: https://context7.com/dickermoshe/convex-dart/llms.txt Provides Dart code examples for setting and clearing authentication tokens using `ConvexClient.instance.setAuth()`. This is crucial for making authenticated calls to your Convex backend, integrating with services like Auth0. ```dart import 'package:your_app/src/convex/client.dart'; // Set authentication token after user login Future onUserLogin(String authToken) async { await ConvexClient.instance.setAuth(token: authToken); print('User authenticated'); } // Clear authentication on logout Future onUserLogout() async { await ConvexClient.instance.setAuth(token: null); print('User logged out'); } // Example with Auth0 integration class AuthService { final auth0 = Auth0('your-domain', 'your-client-id'); Future login() async { final credentials = await auth0.webAuthentication().login(); await ConvexClient.instance.setAuth(token: credentials.idToken); } Future logout() async { await auth0.webAuthentication().logout(); await ConvexClient.instance.setAuth(token: null); } } ``` -------------------------------- ### Define Convex Functions in TypeScript Source: https://github.com/dickermoshe/convex-dart/blob/master/convex_dart/README.md This example demonstrates defining Convex functions (queries and mutations) in TypeScript. It includes type definitions for arguments and return values using `v` from `convex/values` and shows basic database operations like querying, inserting, and updating records. ```typescript // convex/tasks.ts import { query, mutation } from "./_generated/server"; import { v } from "convex/values"; export const getTasks = query({ args: {}, returns: v.array(v.object({ id: v.id("tasks"), title: v.string(), completed: v.boolean(), createdAt: v.number(), })), handler: async (ctx) => { return await ctx.db.query("tasks").collect(); }, }); export const createTask = mutation({ args: { title: v.string(), }, returns: v.id("tasks"), handler: async (ctx, { title }) => { return await ctx.db.insert("tasks", { title, completed: false, createdAt: Date.now(), }); }, }); export const toggleTaskCompletion = mutation({ args: { id: v.id("tasks"), }, handler: async (ctx, { id }) => { const task = await ctx.db.get(id); if (!task) { throw new Error("Task not found"); } await ctx.db.patch(id, { completed: !task.completed, }); }, }); ``` -------------------------------- ### Handle Convex Errors in Dart Source: https://context7.com/dickermoshe/convex-dart/llms.txt Demonstrates how to catch and handle `ConvexError` (application-specific) and `ConvexClientError` (client-side) exceptions in Dart for robust error management. It includes examples for both direct function calls and stream listeners, showing how to inspect error messages and data. ```dart import 'package:convex_dart/convex_dart.dart'; Future safeOperation() async { try { await createTask((text: 'New task', isCompleted: Optional.undefined())); } on ConvexError catch (e) { // Application errors from TypeScript ConvexError print('Application error: ${e.message}'); print('Error data: ${e.data}'); // Handle specific error codes from backend if (e.data is Map) { final code = e.data['code']; switch (code) { case 'VALIDATION_ERROR': print('Invalid input'); break; case 'UNAUTHORIZED': print('Please log in'); break; default: print('Unknown error'); } } } on ConvexClientError catch (e) { // Network, auth, or internal client errors print('Client error: ${e.message}'); // Retry logic, show offline banner, etc. } } // Stream error handling getAllTasksStream().listen( (data) => print('Tasks: ${data.body}'), onError: (error) { if (error is ConvexError) { print('Backend error: ${error.message}'); } else if (error is ConvexClientError) { print('Connection error: ${error.message}'); } }, ); ``` -------------------------------- ### CMake Project Setup and CargoKit Integration Source: https://github.com/dickermoshe/convex-dart/blob/master/convex_dart/linux/CMakeLists.txt This snippet configures the CMake build for the convex-dart project. It sets the minimum required CMake version to 3.10, defines the project name, and integrates Rust code using the CargoKit CMake module. It also lists the bundled libraries, including the CargoKit-generated library. ```cmake cmake_minimum_required(VERSION 3.10) set(PROJECT_NAME "convex_dart") project(${PROJECT_NAME} LANGUAGES CXX) include("../cargokit/cmake/cargokit.cmake") apply_cargokit(${PROJECT_NAME} ../rust convex_dart "") set(convex_dart_bundled_libraries "${${PROJECT_NAME}_cargokit_lib}" PARENT_SCOPE ) ``` -------------------------------- ### Generate Dart client code with convex_dart_cli Source: https://github.com/dickermoshe/convex-dart/blob/master/convex_dart_cli/README.md Shows the basic command to initiate the generation of Dart client code from your Convex backend schema using the convex_dart_cli. ```bash dart run convex_dart_cli generate ``` -------------------------------- ### Configure cargokit.yaml for Precompiled Binaries Source: https://github.com/dickermoshe/convex-dart/blob/master/convex_dart/cargokit/docs/precompiled_binaries.md Specifies the configuration for precompiled binaries in the Rust crate. It includes the URL prefix for downloading binaries and the public key for verification. ```yaml precompiled_binaries: # Uri prefix used when downloading precompiled binaries. url_prefix: https://github.com///releases/download/precompiled_ # Public key for verifying downloaded precompiled binaries. public_key: ``` -------------------------------- ### Generate Dart client code with custom paths and production mode Source: https://github.com/dickermoshe/convex-dart/blob/master/convex_dart_cli/README.md Illustrates advanced usage of the convex_dart_cli for generating Dart client code, allowing specification of custom Convex project paths, output directories, and enabling production mode. ```bash # Specify custom paths dart run convex_dart_cli generate --js ./my-convex-project --output ./lib/src/api # Production mode dart run convex_dart_cli generate --prod ``` -------------------------------- ### Generate Key-Pair with build_tool Source: https://github.com/dickermoshe/convex-dart/blob/master/convex_dart/cargokit/docs/precompiled_binaries.md Generates a private and public key pair using the `build_tool` command. The private key is for signing binaries and should be kept secret, while the public key is used in `cargokit.yaml` for verification. ```dart dart run build_tool gen-key ``` -------------------------------- ### Client Initialization Source: https://context7.com/dickermoshe/convex-dart/llms.txt Initializes the singleton Convex client instance with your deployment URL. This must be called before any other Convex operations. ```APIDOC ## Initialize Convex Client ### Description Initializes the singleton Convex client instance with your deployment URL. This must be called before any other Convex operations. The method initializes the underlying Rust FFI library and creates a connection to your Convex deployment. ### Method `init()` ### Endpoint N/A (Client-side initialization) ### Parameters None ### Request Example ```dart import 'package:flutter/material.dart'; import 'package:your_app/src/convex/client.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); // Initialize Convex client with your deployment URL await ConvexClient.init(); runApp(MyApp()); } ``` ### Response N/A (Initialization is asynchronous and doesn't return a value directly.) ### Response Example N/A ``` -------------------------------- ### Define CMake Project and Minimum Version Source: https://github.com/dickermoshe/convex-dart/blob/master/example/windows/runner/CMakeLists.txt This code sets the minimum required version for CMake and defines the project named 'runner' with CXX language support. It's the starting point for building the Flutter runner application using CMake. ```cmake cmake_minimum_required(VERSION 3.14) project(runner LANGUAGES CXX) ``` -------------------------------- ### Initializing ConvexClient in Dart Source: https://github.com/dickermoshe/convex-dart/blob/master/convex_dart/README.md Provides a code snippet for initializing the `ConvexClient` in Dart. It emphasizes the importance of calling `ConvexClient.init()` before utilizing any other functions provided by the client to avoid 'ConvexClient not initialized' errors. ```dart // Ensure you call init() before using any functions await ConvexClient.init(); ``` -------------------------------- ### Initialize Convex Client - Dart Source: https://context7.com/dickermoshe/convex-dart/llms.txt Initializes the singleton Convex client instance with your deployment URL. This method must be called before any other Convex operations, establishing a connection to your Convex deployment and initializing the underlying Rust FFI library. ```dart import 'package:flutter/material.dart'; import 'package:your_app/src/convex/client.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); // Initialize Convex client with your deployment URL await ConvexClient.init(); runApp(MyApp()); } ``` -------------------------------- ### Initialize ConvexClient in Flutter App Source: https://github.com/dickermoshe/convex-dart/blob/master/convex_dart/README.md This Dart snippet demonstrates the initialization of the `ConvexClient` within a Flutter application's `main` function. It ensures that Flutter's binding is initialized before calling `ConvexClient.init()`, which is necessary for establishing the connection to the Convex backend. ```dart // main.dart import 'package:flutter/material.dart'; import 'package:your_app/src/convex/client.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); // Initialize Convex client await ConvexClient.init(); runApp(MyApp()); } ``` -------------------------------- ### Define Helper Function: list_prepend (CMake) Source: https://github.com/dickermoshe/convex-dart/blob/master/example/linux/flutter/CMakeLists.txt This CMake function prepends a given prefix to each element in a list. It is used to create a new list with the prefix added to every item, compatible with 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() ``` -------------------------------- ### Convex to Dart Type Mapping Reference Source: https://context7.com/dickermoshe/convex-dart/llms.txt A reference guide detailing the automatic mapping between Convex data types and their corresponding Dart equivalents provided by the `convex_dart` package. It covers primitive types, IDs, optionals, unions, arrays, records, and objects, ensuring seamless data serialization and deserialization. ```dart // Convex v.string() -> Dart String String name = 'John'; // Convex v.number() -> Dart double double price = 19.99; // Convex v.boolean() -> Dart bool bool isActive = true; // Convex v.int64() -> Dart int int count = 42; // Convex v.bytes() -> Dart Uint8ListWithEquality Uint8ListWithEquality data = Uint8ListWithEquality.fromList([1, 2, 3, 4]); // Convex v.id("table") -> Generated TableId type TasksId taskId = TasksId('abc123'); // Convex v.optional(T) -> Optional Optional nickname = Optional.defined('Johnny'); Optional missing = Optional.undefined(); // Convex v.union(A, B, C) -> Union3 Union2 result = await getTask((id: taskId)).then((r) => r.body); // Convex v.array(T) -> IList (immutable) IList tasks = IList([task1, task2]); // Convex v.record(K, V) -> IMap (immutable) IMap scores = IMap({'alice': 100, 'bob': 95}); // Convex v.object({...}) -> Generated record type // Returns named record with typed fields ``` -------------------------------- ### Find and Link GTK, GLIB, GIO Libraries (CMake) Source: https://github.com/dickermoshe/convex-dart/blob/master/example/linux/flutter/CMakeLists.txt This section finds the necessary PkgConfig modules (GTK, GLIB, GIO) and configures them as imported targets for linking. It ensures the project has the required system-level dependencies for Flutter Linux GTK. ```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) ``` -------------------------------- ### Profile Build Mode Settings Source: https://github.com/dickermoshe/convex-dart/blob/master/example/windows/CMakeLists.txt Configures linker and compiler flags for the 'Profile' build mode by inheriting settings from the 'Release' build mode. This ensures consistent performance optimization across profile and release 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}") ``` -------------------------------- ### Usage and Pattern Matching of User Profile in Dart Source: https://github.com/dickermoshe/convex-dart/blob/master/convex_dart/README.md Demonstrates how to call the `getUserProfile` query from Dart and use type-safe pattern matching to handle the different union types (premium, free, or null) returned by the query. This ensures robust handling of various user profile structures. ```dart // Usage in Dart final profile = await api.users.getUserProfile( (userId: UsersId("user123")) ); // Type-safe pattern matching profile?.split( (premium) { print('Premium user: ${premium.user.name}'); print('Plan: ${premium.user.subscription.plan}'); }, (free) { print('Free user: ${free.user.name}'); if (free.user.trialEndsAt.isDefined) { print('Trial ends: ${free.user.trialEndsAt.value}'); } }, () => print('User not found'), ); ``` -------------------------------- ### Cargokit build-tool Configuration (YAML) Source: https://github.com/dickermoshe/convex-dart/blob/master/convex_dart/cargokit/docs/architecture.md Configuration for the Rust crate using `cargokit.yaml`. It allows specifying Cargo toolchains, extra flags for debug and release builds, and settings for precompiled binaries including URL prefix and public key for verification. ```yaml cargo: debug: # Configuration of cargo execution during debug builds toolchain: stable # default release: # Configuration of cargo execution for release builds toolchain: nightly # rustup will be invoked with nightly toolchain extra_flags: # extra arguments passed to cargo build - -Z - build-std=panic_abort,std # If crate ships with precompiled binaries, they can be configured here. precompiled_binaries: # Uri prefix used when downloading precompiled binaries. url_prefix: https://github.com/superlistapp/super_native_extensions/releases/download/precompiled_ # Public key for verifying downloaded precompiled binaries. public_key: 3a257ef1c7d72d84225ac4658d24812ada50a7a7a8a2138c2a91353389fdc514 ``` -------------------------------- ### Configure C++ Executable Target with Flutter and GTK Dependencies Source: https://github.com/dickermoshe/convex-dart/blob/master/example/linux/runner/CMakeLists.txt This snippet defines the main C++ executable for the application, lists its source files, applies standard build settings, and links necessary libraries such as Flutter and PkgConfig::GTK. It also sets include directories and application ID definitions. ```cmake cmake_minimum_required(VERSION 3.13) project(runner LANGUAGES CXX) # Define the application target. To change its name, change BINARY_NAME in the # top-level CMakeLists.txt, not the value here, or `flutter run` will no longer # work. # # Any new source files that you add to the application should be added here. add_executable(${BINARY_NAME} "main.cc" "my_application.cc" "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" ) # Apply the standard set of build settings. This can be removed for applications # that need different build settings. apply_standard_settings(${BINARY_NAME}) # Add preprocessor definitions for the application ID. add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}") # Add dependency libraries. Add any application-specific dependencies here. target_link_libraries(${BINARY_NAME} PRIVATE flutter) target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK) target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") ``` -------------------------------- ### Runtime Output Directory Configuration Source: https://github.com/dickermoshe/convex-dart/blob/master/example/linux/CMakeLists.txt Configures the runtime output directory for the main binary (`${BINARY_NAME}`). It places the executable in a subdirectory to prevent users from running unbundled copies. ```cmake set_target_properties(${BINARY_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/intermediates_do_not_run" ) ``` -------------------------------- ### Run Tests in Convex Dart Project Source: https://github.com/dickermoshe/convex-dart/blob/master/convex_dart/rust/CONTRIBUTING.md This command is used to run tests for a specific crate within the Convex Dart project. Ensure you replace `{crate}` with the actual name of the crate you wish to test. This helps maintain code quality and identify potential issues before integration. ```bash cargo test -p {crate} ``` -------------------------------- ### Real-time Subscriptions with Dart Streams Source: https://context7.com/dickermoshe/convex-dart/llms.txt Demonstrates how to create real-time subscriptions to Convex queries using Dart streams. The `StreamBuilder` widget automatically updates the UI when data changes. Ensure the `getAllTasksStream` function is correctly defined and imported. ```dart import 'package:flutter/material.dart'; import 'package:your_app/src/convex/functions/tasks.dart'; class TaskListPage extends StatelessWidget { @override Widget build(BuildContext context) { return StreamBuilder( // Subscribe to real-time task updates stream: getAllTasksStream().distinct(), // Use distinct() to prevent duplicate events builder: (context, snapshot) { if (snapshot.hasError) { final error = snapshot.error; if (error is ConvexError) { return Text('App error: ${error.message}'); } else if (error is ConvexClientError) { return Text('Connection error: ${error.message}'); } return Text('Error: $error'); } if (!snapshot.hasData) { return CircularProgressIndicator(); } final tasks = snapshot.data!.body; return ListView.builder( itemCount: tasks.length, itemBuilder: (context, index) { final task = tasks[index]; return ListTile( title: Text(task.text), trailing: Checkbox( value: task.isCompleted, onChanged: (_) => toggleTaskCompletion((id: task.id))) ); }, ); }, ), ); } } ``` -------------------------------- ### Apply Standard Build Settings Source: https://github.com/dickermoshe/convex-dart/blob/master/example/windows/runner/CMakeLists.txt This function applies a standard set of build settings to the executable. It configures the build process for consistency. Different build settings can be used by removing this line. ```cmake apply_standard_settings(${BINARY_NAME}) ``` -------------------------------- ### Define Flutter Tool Backend Custom Command (CMake) Source: https://github.com/dickermoshe/convex-dart/blob/master/example/linux/flutter/CMakeLists.txt This custom command uses `flutter_tools` to generate the Flutter library and header files. It is designed to run every time due to a phony output target, as directly determining inputs/outputs for the Flutter tool is not straightforward. It sets environment variables and executes the `tool_backend.sh` script. ```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 ) add_custom_target(flutter_assemble DEPENDS "${FLUTTER_LIBRARY}" ${FLUTTER_LIBRARY_HEADERS} ) ``` -------------------------------- ### Project-Level CMake Configuration Source: https://github.com/dickermoshe/convex-dart/blob/master/example/windows/CMakeLists.txt Sets up the minimum CMake version, project name, and languages. It also defines the executable name and opts into modern CMake behaviors to ensure compatibility with recent CMake versions. ```cmake cmake_minimum_required(VERSION 3.14) project(api LANGUAGES CXX) set(BINARY_NAME "api") cmake_policy(VERSION 3.14...3.25) ``` -------------------------------- ### Create Executable for Flutter Application Source: https://github.com/dickermoshe/convex-dart/blob/master/example/windows/runner/CMakeLists.txt This snippet creates an executable target named after BINARY_NAME. It includes the source files needed for the Flutter application. It also incorporates a WIN32 flag and defines the executable's manifest file. ```cmake 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" ) ``` -------------------------------- ### Build Configuration Options Source: https://github.com/dickermoshe/convex-dart/blob/master/example/windows/CMakeLists.txt Defines build configuration types (Debug, Profile, Release) based on whether the generator supports multi-configuration builds. It also 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() ``` -------------------------------- ### Disabling Precompiled Binaries for Convex Dart (YAML) Source: https://github.com/dickermoshe/convex-dart/blob/master/convex_dart/README.md Illustrates how to disable the automatic download of precompiled binaries for the Convex Rust client by setting `use_precompiled_binaries` to `false` in a `cargokit_options.yaml` file. This is useful for building from source, especially when encountering issues with precompiled binaries or requiring build customization. ```yaml use_precompiled_binaries: false ``` -------------------------------- ### CMake Configuration for Flutter Build Steps Source: https://github.com/dickermoshe/convex-dart/blob/master/example/windows/flutter/CMakeLists.txt This snippet outlines the primary CMake configuration for Flutter-level build steps. It sets up essential variables, includes generated configuration, and defines the Flutter library and its headers. It is intended to be managed by the Flutter tool and not edited directly. ```cmake cmake_minimum_required(VERSION 3.14) set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") # Configuration provided via flutter tool. include(${EPHEMERAL_DIR}/generated_config.cmake) # TODO: Move the rest of this into files in ephemeral. See # https://github.com/flutter/flutter/issues/57146. set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper") # Set fallback configurations for older versions of the flutter tool. if (NOT DEFINED FLUTTER_TARGET_PLATFORM) set(FLUTTER_TARGET_PLATFORM "windows-x64") endif() # === Flutter Library === set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll") # 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/windows/app.so" PARENT_SCOPE) list(APPEND FLUTTER_LIBRARY_HEADERS "flutter_export.h" "flutter_windows.h" "flutter_messenger.h" "flutter_plugin_registrar.h" "flutter_texture_registrar.h" ) list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/") add_library(flutter INTERFACE) target_include_directories(flutter INTERFACE "${EPHEMERAL_DIR}" ) target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib") add_dependencies(flutter flutter_assemble) ``` -------------------------------- ### CMake Custom Command for Flutter Tool Backend Source: https://github.com/dickermoshe/convex-dart/blob/master/example/windows/flutter/CMakeLists.txt This CMake configuration sets up a custom command to execute the Flutter tool's backend script. It uses a phony output file to ensure the command runs on every build and defines the output files, including the Flutter library, headers, and wrapper sources. This mechanism allows CMake to invoke the Flutter tool for generating necessary build artifacts. ```cmake # === Flutter tool backend === # _phony_ is a non-existent file to force this command to run every time, # since currently there's no way to get a full input/output list from the # flutter tool. set(PHONY_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/_phony_") set_source_files_properties("${PHONY_OUTPUT}" PROPERTIES SYMBOLIC TRUE) add_custom_command( OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} ${CPP_WRAPPER_SOURCES_APP} ${PHONY_OUTPUT} COMMAND ${CMAKE_COMMAND} -E env ${FLUTTER_TOOL_ENVIRONMENT} "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat" ${FLUTTER_TARGET_PLATFORM} $ VERBATIM ) add_custom_target(flutter_assemble DEPENDS "${FLUTTER_LIBRARY}" ${FLUTTER_LIBRARY_HEADERS} ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} ${CPP_WRAPPER_SOURCES_APP} ) ``` -------------------------------- ### Updating Rust Client Submodule in Convex Dart (Bash) Source: https://github.com/dickermoshe/convex-dart/blob/master/convex_dart/README.md Provides the bash command to update the Rust client submodule within the Convex Dart project. It uses `git subtree pull` to fetch changes from the `convex-rs` repository and then requires rerunning the Dart bindings generation. ```bash git subtree pull --prefix convex_dart/rust https://github.com/dickermoshe/convex-rs branch_name --squash flutter_rust_bridge_codegen generate ``` -------------------------------- ### Handling Optional Types in TypeScript and Dart Source: https://github.com/dickermoshe/convex-dart/blob/master/convex_dart/README.md Demonstrates how to use `v.union(v.string(), v.null())` in TypeScript for optional string arguments, which translates to familiar nullable syntax (`String?`) in Dart, avoiding the `Optional` type. This improves developer experience by aligning with Dart's nullable types. ```typescript // Instead of this: args: { name: v.optional(v.string()) } // Consider this: args: { name: v.union(v.string(), v.null()) } ``` ```dart // Results in familiar nullable syntax: final name = args.name; // String? instead of Optional ```