### Install Executable and Data Source: https://github.com/appwrite/playground-for-flutter/blob/master/linux/CMakeLists.txt Installs the main executable to the prefix and the ICU data file to a 'data' subdirectory within the bundle. This prepares the application for deployment. ```cmake set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib") install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" COMPONENT Runtime) install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) ``` -------------------------------- ### Installation Prefix Configuration Source: https://github.com/appwrite/playground-for-flutter/blob/master/linux/CMakeLists.txt Configures the installation prefix, defaulting to a 'bundle' directory within the build directory for relocatable installations. This ensures the application and its resources are installed together. ```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 Configuration for Windows Executable Source: https://github.com/appwrite/playground-for-flutter/blob/master/windows/CMakeLists.txt Configures installation rules for the Windows executable, ensuring support files are placed alongside the executable for in-place running, compatible with Visual Studio builds. ```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}") 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) ``` -------------------------------- ### Install Flutter Library and Bundled Libraries Source: https://github.com/appwrite/playground-for-flutter/blob/master/linux/CMakeLists.txt Installs the main Flutter library and any bundled plugin libraries to the 'lib' directory within the installation bundle. This makes essential runtime components available. ```cmake 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) ``` -------------------------------- ### System Dependencies Source: https://github.com/appwrite/playground-for-flutter/blob/master/linux/CMakeLists.txt Finds and checks for required system-level dependencies using PkgConfig. This example specifically looks for the 'gtk+-3.0' package. ```cmake find_package(PkgConfig REQUIRED) pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) ``` -------------------------------- ### Storage — Upload File Source: https://context7.com/appwrite/playground-for-flutter/llms.txt This example shows how to pick a file using the system file picker and upload it to an Appwrite storage bucket. ```APIDOC ## Storage — Upload File Pick a file with the system file picker and upload it to an Appwrite storage bucket, supporting both web (bytes) and native (file path) environments. ```dart import 'package:appwrite/appwrite.dart'; import 'package:file_picker/file_picker.dart'; import 'package:flutter/foundation.dart' show kIsWeb; import 'package:appwrite/models.dart'; Future uploadFile(Storage storage, User? user) async { // 1. Pick an image file final result = await FilePicker.platform.pickFiles( type: FileType.image, allowMultiple: false, ); if (result == null) return; final picked = result.files.single; // 2. Build InputFile differently for web vs native final InputFile inFile = kIsWeb ? InputFile.fromBytes(filename: picked.name, bytes: picked.bytes!) : InputFile.fromPath(path: picked.path!, filename: picked.name); // 3. Upload to Appwrite Storage try { final file = await storage.createFile( bucketId: ID.custom(bucketId), // 'testBucket' fileId: ID.unique(), file: inFile, permissions: [ // If logged in, only the user can read; otherwise anyone Permission.read(user != null ? Role.user(user.$id) : Role.any()), Permission.write(Role.users()), // any authenticated user can write ], ); print('Uploaded file ID: ${file.$id}'); print('File size: ${file.sizeOriginal} bytes'); } on AppwriteException catch (e) { print('Upload failed: ${e.message}'); } } ``` ``` -------------------------------- ### AOT Library Installation Source: https://github.com/appwrite/playground-for-flutter/blob/master/windows/CMakeLists.txt Installs the Ahead-Of-Time (AOT) compiled library for Profile and Release builds. ```cmake install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" CONFIGURATIONS Profile;Release COMPONENT Runtime) ``` -------------------------------- ### Install AOT Library Source: https://github.com/appwrite/playground-for-flutter/blob/master/linux/CMakeLists.txt Installs the Ahead-Of-Time (AOT) compiled library on non-Debug builds. This optimizes application startup and performance. ```cmake if(NOT CMAKE_BUILD_TYPE MATCHES "Debug") install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) endif() ``` -------------------------------- ### Install Native Assets Source: https://github.com/appwrite/playground-for-flutter/blob/master/linux/CMakeLists.txt Installs native assets provided by packages into the 'lib' directory of the installation bundle. These assets are required for certain plugin functionalities. ```cmake set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/linux/") install(DIRECTORY "${NATIVE_ASSETS_DIR}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) ``` -------------------------------- ### CLI Setup — Platform Registration Source: https://context7.com/appwrite/playground-for-flutter/llms.txt Register each Flutter platform target with Appwrite before running the app. This involves using the `appwrite projects create-platform` command for iOS, Android, macOS, Windows, and Linux. ```APIDOC ## CLI Setup — Platform Registration Register each Flutter platform target with Appwrite before running the app. ### iOS ```bash export PROJECT_ID=playground-for-flutter appwrite projects create-platform \ --project-id $PROJECT_ID \ --type flutter-ios \ --name "io.appwrite.playgroundForFlutter" \ --key "io.appwrite.playgroundForFlutter" ``` ### Android ```bash export PROJECT_ID=playground-for-flutter appwrite projects create-platform \ --project-id $PROJECT_ID \ --type flutter-android \ --name "io.appwrite.playground_for_flutter" \ --key "io.appwrite.playground_for_flutter" ``` ### macOS ```bash export PROJECT_ID=playground-for-flutter appwrite projects create-platform \ --project-id $PROJECT_ID \ --type flutter-macos \ --name "io.appwrite.playgroundForFlutter" \ --key "io.appwrite.playgroundForFlutter" ``` ### Windows / Linux ```bash export PROJECT_ID=playground-for-flutter appwrite projects create-platform --project-id $PROJECT_ID --type flutter-windows --name "playground_for_flutter" --key "playground_for_flutter" appwrite projects create-platform --project-id $PROJECT_ID --type flutter-linux --name "playground_for_flutter" --key "playground_for_flutter" ``` ``` -------------------------------- ### Clean Build Bundle Directory Source: https://github.com/appwrite/playground-for-flutter/blob/master/linux/CMakeLists.txt Installs a custom command to recursively remove the build bundle directory before installation. This ensures a clean state for each installation. ```cmake install(CODE " file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\") " COMPONENT Runtime) ``` -------------------------------- ### Library Installation Path Source: https://github.com/appwrite/playground-for-flutter/blob/master/linux/CMakeLists.txt Configures the runtime search path for bundled libraries to be relative to the executable's location. This is crucial for ensuring the application can find its dependencies after installation. ```cmake set(CMAKE_INSTALL_RPATH "$ORIGIN/lib") ``` -------------------------------- ### Flutter Assets Installation Source: https://github.com/appwrite/playground-for-flutter/blob/master/windows/CMakeLists.txt Installs Flutter assets, ensuring the assets directory is completely 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) ``` -------------------------------- ### Realtime — Subscribe & Unsubscribe Source: https://context7.com/appwrite/playground-for-flutter/llms.txt This example demonstrates how to open a persistent WebSocket connection to Appwrite Realtime to receive live events for files and documents, and how to unsubscribe. ```APIDOC ## Realtime — Subscribe & Unsubscribe Open a persistent WebSocket connection to Appwrite Realtime to receive live events for files and documents. ```dart import 'dart:convert'; import 'package:appwrite/appwrite.dart'; RealtimeSubscription? _subscription; void subscribe(Client client, void Function(String event) onEvent) { final realtime = Realtime(client); // Subscribe to both 'files' and 'documents' channels _subscription = realtime.subscribe(['files', 'documents']); _subscription!.stream.listen((RealtimeMessage data) { final eventJson = jsonEncode(data.toMap()); print('Realtime event: $eventJson'); // Example payload: // {"events":["databases.default.collections.usernames.documents.*.create"], // "payload":{\"username\":\"hello2\",\"$id\":\"...\",\"$collectionId\":\"usernames\",...}} onEvent(eventJson); }); } void unsubscribe() { _subscription?.close(); _subscription = null; print('Realtime subscription closed'); } ``` ``` -------------------------------- ### Databases — Create Document Source: https://context7.com/appwrite/playground-for-flutter/llms.txt This example demonstrates how to insert a new document into an Appwrite collection with specified permissions. ```APIDOC ## Databases — Create Document Insert a new document into an Appwrite collection with fine-grained permissions. ```dart import 'package:appwrite/appwrite.dart'; Future createDocument(Databases databases) async { try { final document = await databases.createDocument( databaseId: ID.custom(databaseId), // 'default' collectionId: ID.custom(collectionId), // 'usernames' documentId: ID.unique(), // auto-generated unique ID data: {'username': 'hello2'}, permissions: [ Permission.read(Role.any()), // anyone can read Permission.write(Role.any()), // anyone can write ], ); print('Document created: ${document.$id}'); print(document.toMap()); // Output: {$id: '...', $collectionId: 'usernames', username: 'hello2', ...} } on AppwriteException catch (e) { print('Create document failed: ${e.message}'); } } ``` ``` -------------------------------- ### Functions — Create Execution Source: https://context7.com/appwrite/playground-for-flutter/llms.txt Invoke a deployed Appwrite Function synchronously and read its response body. This example shows how to use the `createExecution` method to call a function with POST method, custom headers, and a JSON body. ```APIDOC ## Functions — Create Execution Invoke a deployed Appwrite Function synchronously and read its response body. ### Method POST ### Endpoint /v1/functions/{functionId}/executions ### Parameters #### Path Parameters - **functionId** (string) - Required - Function ID. #### Headers - **Content-Type** (string) - Required - Content type of the request body. #### Request Body - **key** (string) - Required - Example key for the request body. ### Request Example ```dart await functions.createExecution( functionId: 'my-function-id', method: ExecutionMethod.pOST, headers: {'Content-Type': 'application/json'}, body: jsonEncode({'key': 'value'}) ); ``` ### Response #### Success Response (200) - **status** (string) - The status of the execution ('completed' or 'failed'). - **responseBody** (string) - The JSON string response from the function. - **duration** (float) - The duration of the function execution in seconds. #### Response Example ```json { "status": "completed", "responseBody": "{\"message\": \"Hello from function\"}", "duration": 0.123 } ``` ``` -------------------------------- ### Storage — Get File View (Display Image) Source: https://context7.com/appwrite/playground-for-flutter/llms.txt This example shows how to download raw file bytes from Appwrite Storage and display them as an image in a Flutter widget. ```APIDOC ## Storage — Get File View (Display Image) Download raw file bytes from Appwrite Storage and display them as an image in a Flutter widget. ```dart import 'package:appwrite/appwrite.dart'; import 'package:flutter/material.dart'; Widget buildFileImage(Storage storage, String fileId) { return FutureBuilder( future: storage.getFileView( bucketId: ID.custom(bucketId), // 'testBucket' fileId: ID.custom(fileId), ), builder: (context, snapshot) { if (snapshot.hasData) { return Image.memory(snapshot.data!); // render raw bytes as image } if (snapshot.hasError) { if (snapshot.error is AppwriteException) { print((snapshot.error as AppwriteException).message); } return const Text('Failed to load image'); } return const CircularProgressIndicator(); }, ); } ``` ``` -------------------------------- ### Configure Flutter library and headers Source: https://github.com/appwrite/playground-for-flutter/blob/master/linux/flutter/CMakeLists.txt Defines the Flutter library path and ICU data file, and appends a list of Flutter library headers. These are published to the parent scope for use in the install step. ```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) 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/") ``` -------------------------------- ### Copy Constants File Source: https://github.com/appwrite/playground-for-flutter/blob/master/README.md Copies the default constants file to the active constants file using the cp command. This is a setup step for the Flutter application. ```bash cp lib/constants.dart.default lib/constants.dart ``` -------------------------------- ### Get Current Appwrite Account Source: https://context7.com/appwrite/playground-for-flutter/llms.txt Retrieve the currently authenticated user's profile. Falls back gracefully when no session exists, printing the user's details or an error message. ```dart import 'package:appwrite/appwrite.dart'; import 'package:appwrite/models.dart'; Future getAccount(Account account) async { try { final User user = await account.get(); if (user.email.isEmpty) { print('Logged in as anonymous user: ${user.$id}'); } else { print('Logged in as: ${user.name} <${user.email}>'); } } on AppwriteException catch (e) { // e.g. "User (role: guests) missing scope (account)" print('No active session: ${e.message}'); } } ``` -------------------------------- ### Storage: Get File View (Display Image) Source: https://context7.com/appwrite/playground-for-flutter/llms.txt Downloads raw file bytes from Appwrite Storage and displays them as an image in a Flutter widget using a FutureBuilder. Handles loading states and errors. Requires bucket and file IDs. ```dart import 'package:appwrite/appwrite.dart'; import 'package:flutter/material.dart'; Widget buildFileImage(Storage storage, String fileId) { return FutureBuilder( future: storage.getFileView( bucketId: ID.custom(bucketId), // 'testBucket' fileId: ID.custom(fileId), ), builder: (context, snapshot) { if (snapshot.hasData) { return Image.memory(snapshot.data!); // render raw bytes as image } if (snapshot.hasError) { if (snapshot.error is AppwriteException) { print((snapshot.error as AppwriteException).message); } return const Text('Failed to load image'); } return const CircularProgressIndicator(); }, ); } ``` -------------------------------- ### Deploy Resources and Run App Source: https://context7.com/appwrite/playground-for-flutter/llms.txt Deploy your database collection and storage bucket using the Appwrite CLI, create a test user, and then run the Flutter app. ```bash # 2. Deploy the database collection and storage bucket via Appwrite CLI appwrite deploy collection --all --yes appwrite deploy bucket --all --yes # 3. Create a test user appwrite users create \ --user-id "unique()" \ --email "user@appwrite.io" \ --password "password" \ --name "Test User" # 4. Run the Flutter app flutter run lib/main.dart ``` -------------------------------- ### Initialize Appwrite Client and Services Source: https://context7.com/appwrite/playground-for-flutter/llms.txt Initialize the Appwrite Client and service objects once in main(), then pass them down to widgets. Includes optional dev key configuration and a ping to verify connectivity. ```dart import 'package:appwrite/appwrite.dart'; import 'constants.dart'; void main() { WidgetsFlutterBinding.ensureInitialized(); // Create and configure the shared client final client = Client() .setEndpoint(endpoint) // e.g. 'https://fra.cloud.appwrite.io/v1' .setProject(project); // e.g. 'playground-for-flutter' // Optional: set a dev key to bypass rate limits / permission checks during development if (devKey.isNotEmpty) { client.setDevKey(devKey); } // Instantiate one service object per Appwrite service final account = Account(client); final storage = Storage(client); final databases = Databases(client); final functions = Functions(client); // Verify connectivity client.ping(); runApp(MaterialApp( home: Playground( client: client, account: account, storage: storage, database: databases, functions: functions, ), )); } ``` -------------------------------- ### Deploy Appwrite Bucket Source: https://github.com/appwrite/playground-for-flutter/blob/master/README.md Deploys all bucket configurations for the Appwrite project using the CLI. The --yes flag bypasses confirmation prompts. ```bash appwrite deploy bucket --all --yes ``` -------------------------------- ### Deploy Appwrite Database and Collection Source: https://github.com/appwrite/playground-for-flutter/blob/master/README.md Deploys the database and collection configurations for the Appwrite project using the CLI. The --yes flag bypasses confirmation prompts. ```bash appwrite deploy collection --all --yes ``` -------------------------------- ### Project Initialization and Settings Source: https://github.com/appwrite/playground-for-flutter/blob/master/windows/CMakeLists.txt Sets the minimum CMake version, project name, and executable name. It also explicitly opts into modern CMake behaviors. ```cmake cmake_minimum_required(VERSION 3.14) project(playground_for_flutter LANGUAGES CXX) set(BINARY_NAME "playground_for_flutter") cmake_policy(VERSION 3.14...3.25) ``` -------------------------------- ### Cross-Building System Root Source: https://github.com/appwrite/playground-for-flutter/blob/master/linux/CMakeLists.txt Sets up the sysroot and find paths for cross-compiling. This is used when building for a different architecture or environment 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() ``` -------------------------------- ### Create Appwrite Flutter Platforms (Windows CMD) Source: https://github.com/appwrite/playground-for-flutter/blob/master/README.md Creates multiple Flutter platforms (iOS, Android, macOS, Windows, Linux) for the Appwrite project using the CLI. Ensure the PROJECT_ID is set. ```cmd appwrite projects create-platform --project-id %PROJECT_ID% --type flutter-ios --name "io.appwrite.playgroundForFlutter" --key "io.appwrite.playgroundForFlutter" appwrite projects create-platform --project-id %PROJECT_ID% --type flutter-android --name "io.appwrite.playground_for_flutter" --key "io.appwrite.playground_for_flutter" appwrite projects create-platform --project-id %PROJECT_ID% --type flutter-macos --name "io.appwrite.playgroundForFlutter" --key "io.appwrite.playgroundForFlutter" appwrite projects create-platform --project-id %PROJECT_ID% --type flutter-windows --name "playground_for_flutter" --key "playground_for_flutter" appwrite projects create-platform --project-id %PROJECT_ID% --type flutter-linux --name "playground_for_flutter" --key "playground_for_flutter" ``` -------------------------------- ### Find and link GTK, GLIB, and GIO modules Source: https://github.com/appwrite/playground-for-flutter/blob/master/linux/flutter/CMakeLists.txt This snippet uses PkgConfig to find and check for the required GTK, GLIB, and GIO libraries, making them available for linking. ```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) ``` -------------------------------- ### Create Appwrite Flutter Platforms (Unix/MacOS/Linux) Source: https://github.com/appwrite/playground-for-flutter/blob/master/README.md Creates multiple Flutter platforms (iOS, Android, macOS, Windows, Linux) for the Appwrite project using the CLI. Ensure the PROJECT_ID is set. ```bash appwrite projects create-platform --project-id $PROJECT_ID --type flutter-ios --name "io.appwrite.playgroundForFlutter" --key "io.appwrite.playgroundForFlutter" appwrite projects create-platform --project-id $PROJECT_ID --type flutter-android --name "io.appwrite.playground_for_flutter" --key "io.appwrite.playground_for_flutter" appwrite projects create-platform --project-id $PROJECT_ID --type flutter-macos --name "io.appwrite.playgroundForFlutter" --key "io.appwrite.playgroundForFlutter" appwrite projects create-platform --project-id $PROJECT_ID --type flutter-windows --name "playground_for_flutter" --key "playground_for_flutter" appwrite projects create-platform --project-id $PROJECT_ID --type flutter-linux --name "playground_for_flutter" --key "playground_for_flutter" ``` -------------------------------- ### Apply Standard Build Settings Source: https://github.com/appwrite/playground-for-flutter/blob/master/linux/runner/CMakeLists.txt Applies a predefined set of build settings to the specified target. This can be customized for applications requiring different build configurations. ```cmake apply_standard_settings(${BINARY_NAME}) ``` -------------------------------- ### Create Anonymous Appwrite Session Source: https://context7.com/appwrite/playground-for-flutter/llms.txt Create a guest session without requiring credentials. This is useful for onboarding flows. Prints the session ID on success or an error message on failure. ```dart Future loginAnonymously(Account account) async { try { final session = await account.createAnonymousSession(); print('Anonymous session created: ${session.$id}'); // Now call account.get() to fetch the anonymous User object } on AppwriteException catch (e) { print('Anonymous login failed: ${e.message}'); } } ``` -------------------------------- ### Runner Subdirectory Source: https://github.com/appwrite/playground-for-flutter/blob/master/linux/CMakeLists.txt Includes the build configuration for the application's runner. This is typically where the main application logic and entry point are defined. ```cmake add_subdirectory("runner") ``` -------------------------------- ### Project and Executable Naming Source: https://github.com/appwrite/playground-for-flutter/blob/master/linux/CMakeLists.txt Sets the minimum CMake version, project name, and the executable's on-disk name. Adjust BINARY_NAME to change the application's file name. ```cmake cmake_minimum_required(VERSION 3.13) project(runner LANGUAGES CXX) set(BINARY_NAME "playground_for_flutter") set(APPLICATION_ID "io.appwrite.playground_for_flutter") ``` -------------------------------- ### Create Appwrite Flutter Platforms (Windows PowerShell) Source: https://github.com/appwrite/playground-for-flutter/blob/master/README.md Creates multiple Flutter platforms (iOS, Android, macOS, Windows, Linux) for the Appwrite project using the CLI. Ensure the PROJECT_ID is set. ```powershell appwrite projects create-platform --project-id $env:PROJECT_ID --type flutter-ios --name "io.appwrite.playgroundForFlutter" --key "io.appwrite.playgroundForFlutter" appwrite projects create-platform --project-id $env:PROJECT_ID --type flutter-android --name "io.appwrite.playground_for_flutter" --key "io.appwrite.playground_for_flutter" appwrite projects create-platform --project-id $env:PROJECT_ID --type flutter-macos --name "io.appwrite.playgroundForFlutter" --key "io.appwrite.playgroundForFlutter" appwrite projects create-platform --project-id $env:PROJECT_ID --type flutter-windows --name "playground_for_flutter" --key "playground_for_flutter" appwrite projects create-platform --project-id $env:PROJECT_ID --type flutter-linux --name "playground_for_flutter" --key "playground_for_flutter" ``` -------------------------------- ### Login with Email and Password Source: https://context7.com/appwrite/playground-for-flutter/llms.txt Authenticates a user using their email and password. Ensure user credentials are securely stored. ```dart Future loginWithEmail(Account account) async { try { final session = await account.createEmailPasswordSession( email: userEmail, // 'user@appwrite.io' password: userPassword, // 'password' ); print('Session ID: ${session.$id}'); print('User ID: ${session.userId}'); } on AppwriteException catch (e) { print('Email login failed: ${e.message}'); } } ``` -------------------------------- ### Run Flutter App Source: https://github.com/appwrite/playground-for-flutter/blob/master/README.md Executes the Flutter application using the flutter run command, specifying the main dart file to run. ```bash flutter run lib/main.dart ``` -------------------------------- ### Sign In With Apple (Native iOS/macOS) Source: https://context7.com/appwrite/playground-for-flutter/llms.txt Implement native Apple Sign-In for iOS and macOS. This method exchanges Apple credentials via an Appwrite Function to create a secure Appwrite session. ```APIDOC ## Sign In With Apple (Native iOS/macOS) Use the native Apple Sign-In button on iOS/macOS, exchange the Apple credential via an Appwrite Function, then create a session from the returned token. ```dart import 'dart:convert'; import 'dart:io'; import 'package:appwrite/enums.dart'; import 'package:flutter/foundation.dart'; import 'package:sign_in_with_apple/sign_in_with_apple.dart'; Future nativeAppleSignIn(Account account, Functions functions) async { // Only show native button on iOS / macOS (not web) if (kIsWeb || (!Platform.isIOS && !Platform.isMacOS)) return; // 1. Get Apple credential from the OS final credential = await SignInWithApple.getAppleIDCredential( scopes: [ AppleIDAuthorizationScopes.email, AppleIDAuthorizationScopes.fullName, ], ); // 2. Build payload for the Appwrite Function final body = {'code': credential.authorizationCode}; if (credential.givenName?.isNotEmpty ?? false) body['firstName'] = credential.givenName!; if (credential.familyName?.isNotEmpty ?? false) body['lastName'] = credential.familyName!; // 3. Execute the sign-in-with-apple Appwrite Function final execution = await functions.createExecution( functionId: signInWithAppleFunctionId, // 'sign-in-with-apple' method: ExecutionMethod.pOST, headers: {'Content-Type': 'application/json'}, body: jsonEncode(body), ); print('Function status: ${execution.status}'); // 4. Use the returned token to create an Appwrite session final token = json.decode(execution.responseBody) as Map; await account.createSession( userId: token['userId'] as String, secret: token['secret'] as String, ); print('Apple session created for user: ${token['userId']}'); } ``` ``` -------------------------------- ### Copy Constants Template Source: https://context7.com/appwrite/playground-for-flutter/llms.txt Copy the default constants file to your project and fill in your Appwrite project details. ```bash # 1. Copy the constants template cp lib/constants.dart.default lib/constants.dart ``` -------------------------------- ### Storage: Upload File Source: https://context7.com/appwrite/playground-for-flutter/llms.txt Picks an image file using the system file picker and uploads it to an Appwrite storage bucket. Supports both web (bytes) and native (file path) environments. Requires a bucket ID and optionally user information for permissions. ```dart import 'package:appwrite/appwrite.dart'; import 'package:file_picker/file_picker.dart'; import 'package:flutter/foundation.dart' show kIsWeb; import 'package:appwrite/models.dart'; Future uploadFile(Storage storage, User? user) async { // 1. Pick an image file final result = await FilePicker.platform.pickFiles( type: FileType.image, allowMultiple: false, ); if (result == null) return; final picked = result.files.single; // 2. Build InputFile differently for web vs native final InputFile inFile = kIsWeb ? InputFile.fromBytes(filename: picked.name, bytes: picked.bytes!) : InputFile.fromPath(path: picked.path!, filename: picked.name); // 3. Upload to Appwrite Storage try { final file = await storage.createFile( bucketId: ID.custom(bucketId), // 'testBucket' fileId: ID.unique(), file: inFile, permissions: [ // If logged in, only the user can read; otherwise anyone Permission.read(user != null ? Role.user(user.$id) : Role.any()), Permission.write(Role.users()), // any authenticated user can write ], ); print('Uploaded file ID: ${file.$id}'); print('File size: ${file.sizeOriginal} bytes'); } on AppwriteException catch (e) { print('Upload failed: ${e.message}'); } } ``` -------------------------------- ### Appwrite Configuration Constants Source: https://context7.com/appwrite/playground-for-flutter/llms.txt Fill in your Appwrite endpoint, project ID, and other necessary resource IDs in this file. ```dart // lib/constants.dart — fill in your values const endpoint = 'https://.cloud.appwrite.io/v1'; // Appwrite Cloud or self-hosted URL const project = 'playground-for-flutter'; // Your Appwrite project ID const devKey = ''; // Optional: dev API key for elevated access const userEmail = 'user@appwrite.io'; // Test user email const userPassword = 'password'; // Test user password const databaseId = 'default'; // Appwrite database ID const bucketId = 'testBucket'; // Appwrite storage bucket ID const collectionId = 'usernames'; // Appwrite collection ID const signInWithAppleFunctionId = 'sign-in-with-apple'; // Appwrite Function ID for Apple Sign-In ``` -------------------------------- ### Executable Output Directory Source: https://github.com/appwrite/playground-for-flutter/blob/master/linux/CMakeLists.txt Sets the runtime output directory for the executable to a subdirectory within the build directory. This prevents accidental execution of unbundled copies. ```cmake set_target_properties(${BINARY_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/intermediates_do_not_run" ) ``` -------------------------------- ### Unicode Support Source: https://github.com/appwrite/playground-for-flutter/blob/master/windows/CMakeLists.txt Adds preprocessor definitions to enable Unicode support in the project. ```cmake add_definitions(-DUNICODE -D_UNICODE) ``` -------------------------------- ### Add Include Directories Source: https://github.com/appwrite/playground-for-flutter/blob/master/linux/runner/CMakeLists.txt Specifies the directories from which header files can be included during compilation. ```cmake target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") ``` -------------------------------- ### Register Flutter Platforms with Appwrite CLI Source: https://context7.com/appwrite/playground-for-flutter/llms.txt Register each Flutter platform target with Appwrite using the CLI before running your app. Ensure the PROJECT_ID environment variable is set. ```bash export PROJECT_ID=playground-for-flutter # iOS appwrite projects create-platform \ --project-id $PROJECT_ID \ --type flutter-ios \ --name "io.appwrite.playgroundForFlutter" \ --key "io.appwrite.playgroundForFlutter" # Android appwrite projects create-platform \ --project-id $PROJECT_ID \ --type flutter-android \ --name "io.appwrite.playground_for_flutter" \ --key "io.appwrite.playground_for_flutter" # macOS appwrite projects create-platform \ --project-id $PROJECT_ID \ --type flutter-macos \ --name "io.appwrite.playgroundForFlutter" \ --key "io.appwrite.playgroundForFlutter" # Windows / Linux appwrite projects create-platform --project-id $PROJECT_ID --type flutter-windows --name "playground_for_flutter" --key "playground_for_flutter" appwrite projects create-platform --project-id $PROJECT_ID --type flutter-linux --name "playground_for_flutter" --key "playground_for_flutter" ``` -------------------------------- ### Custom command for Flutter tool backend Source: https://github.com/appwrite/playground-for-flutter/blob/master/linux/flutter/CMakeLists.txt A custom command to execute the Flutter tool backend script. It uses a phony target to ensure it runs on every build, as direct input/output tracking is not feasible. ```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 ) ``` -------------------------------- ### Create Appwrite Test User Source: https://github.com/appwrite/playground-for-flutter/blob/master/README.md Creates a test user with a specific ID, email, password, and name using the Appwrite CLI. The user ID is set to 'unique()' to ensure a new unique ID is generated. ```bash appwrite users create --user-id "unique()" --email "user@appwrite.io" --password "password" --name "Test User" ``` -------------------------------- ### Link Dependency Libraries Source: https://github.com/appwrite/playground-for-flutter/blob/master/linux/runner/CMakeLists.txt Links the necessary libraries for the application, including the Flutter engine and GTK for Linux integration. ```cmake target_link_libraries(${BINARY_NAME} PRIVATE flutter) target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK) ``` -------------------------------- ### Build Configuration for Multi-Config Generators Source: https://github.com/appwrite/playground-for-flutter/blob/master/windows/CMakeLists.txt Defines the available build configurations (Debug, Profile, Release) when using a multi-config generator like Visual Studio. ```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() ``` -------------------------------- ### OAuth2 Session Source: https://context7.com/appwrite/playground-for-flutter/llms.txt Create an OAuth2 session by redirecting the user through a third-party provider like Discord, GitHub, Google, or Apple. This simplifies user authentication by leveraging existing social logins. ```APIDOC ## OAuth2 Session Redirect the user through a third-party OAuth2 provider. ```dart import 'package:appwrite/enums.dart'; import 'package:flutter/foundation.dart' show kIsWeb; import 'package:window_location_href/window_location_href.dart' hide Platform; Future loginWithOAuth(Account account, OAuthProvider provider) async { final Uri? location = href == null ? null : Uri.parse(href!); try { await account.createOAuth2Session( provider: provider, // OAuthProvider.discord / .github / .google / .apple // On web, redirect back to your auth.html callback page success: kIsWeb ? '${location?.origin}/auth.html' : null, failure: '', // Optional: URL to redirect on failure ); // After redirect completes, call account.get() to load user info } on AppwriteException catch (e) { print('OAuth login failed: ${e.message}'); } } // Usage examples: // loginWithOAuth(account, OAuthProvider.discord); // loginWithOAuth(account, OAuthProvider.github); // loginWithOAuth(account, OAuthProvider.google); // loginWithOAuth(account, OAuthProvider.apple); ``` ``` -------------------------------- ### Create Flutter interface library Source: https://github.com/appwrite/playground-for-flutter/blob/master/linux/flutter/CMakeLists.txt Defines an INTERFACE library for Flutter, setting include directories and linking necessary libraries including PkgConfig modules. ```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 ) add_dependencies(flutter flutter_assemble) ``` -------------------------------- ### Set Minimum CMake Version and Project Name Source: https://github.com/appwrite/playground-for-flutter/blob/master/linux/runner/CMakeLists.txt Specifies the minimum required CMake version and defines the project name with supported languages. ```cmake cmake_minimum_required(VERSION 3.13) project(runner LANGUAGES CXX) ``` -------------------------------- ### Add Preprocessor Definitions for Application ID Source: https://github.com/appwrite/playground-for-flutter/blob/master/linux/runner/CMakeLists.txt Adds a preprocessor definition for the application ID, making it available during compilation. ```cmake add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}") ``` -------------------------------- ### Login with OAuth2 Provider Source: https://context7.com/appwrite/playground-for-flutter/llms.txt Initiates an OAuth2 session with a third-party provider like Discord, GitHub, Google, or Apple. For web, specify success and failure redirect URLs. ```dart import 'package:appwrite/enums.dart'; import 'package:flutter/foundation.dart' show kIsWeb; import 'package:window_location_href/window_location_href.dart' hide Platform; Future loginWithOAuth(Account account, OAuthProvider provider) async { final Uri? location = href == null ? null : Uri.parse(href!); try { await account.createOAuth2Session( provider: provider, // OAuthProvider.discord / .github / .google / .apple // On web, redirect back to your auth.html callback page success: kIsWeb ? '${location?.origin}/auth.html' : null, failure: '', // Optional: URL to redirect on failure ); // After redirect completes, call account.get() to load user info } on AppwriteException catch (e) { print('OAuth login failed: ${e.message}'); } } // Usage examples: // loginWithOAuth(account, OAuthProvider.discord); // loginWithOAuth(account, OAuthProvider.github); // loginWithOAuth(account, OAuthProvider.google); // loginWithOAuth(account, OAuthProvider.apple); ``` -------------------------------- ### Realtime: Subscribe & Unsubscribe Source: https://context7.com/appwrite/playground-for-flutter/llms.txt Opens a persistent WebSocket connection to Appwrite Realtime to receive live events for files and documents. Allows subscribing to multiple channels and provides a callback for handling incoming events. Unsubscribing closes the connection. ```dart import 'dart:convert'; import 'package:appwrite/appwrite.dart'; RealtimeSubscription? _subscription; void subscribe(Client client, void Function(String event) onEvent) { final realtime = Realtime(client); // Subscribe to both 'files' and 'documents' channels _subscription = realtime.subscribe(['files', 'documents']); _subscription!.stream.listen((RealtimeMessage data) { final eventJson = jsonEncode(data.toMap()); print('Realtime event: $eventJson'); // Example payload: // {"events":["databases.default.collections.usernames.documents.*.create"], // "payload":{"username":"hello2","$id":"...","$collectionId":"usernames",...}} onEvent(eventJson); }); } void unsubscribe() { _subscription?.close(); _subscription = null; print('Realtime subscription closed'); } ``` -------------------------------- ### Modern CMake Policy Source: https://github.com/appwrite/playground-for-flutter/blob/master/linux/CMakeLists.txt Explicitly opts into modern CMake behaviors to prevent warnings with recent CMake versions. This ensures compatibility and adherence to current best practices. ```cmake cmake_policy(SET CMP0063 NEW) ``` -------------------------------- ### Generated Plugin Inclusion Source: https://github.com/appwrite/playground-for-flutter/blob/master/windows/CMakeLists.txt Includes generated CMake files for managing and building plugins. ```cmake include(flutter/generated_plugins.cmake) ``` -------------------------------- ### Profile Build Mode Linker and Compiler Flags Source: https://github.com/appwrite/playground-for-flutter/blob/master/windows/CMakeLists.txt Sets linker and compiler flags for the Profile build mode, often inheriting settings from the Release mode. ```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}") ``` -------------------------------- ### Email & Password Session Source: https://context7.com/appwrite/playground-for-flutter/llms.txt Authenticate users by creating an email and password session. This method is suitable for traditional username/password login flows. ```APIDOC ## Email & Password Session Authenticate with email and password credentials. ```dart Future loginWithEmail(Account account) async { try { final session = await account.createEmailPasswordSession( email: userEmail, // 'user@appwrite.io' password: userPassword, // 'password' ); print('Session ID: ${session.$id}'); print('User ID: ${session.userId}'); } on AppwriteException catch (e) { print('Email login failed: ${e.message}'); } } ``` ``` -------------------------------- ### Post Authentication Message Handler (JavaScript) Source: https://github.com/appwrite/playground-for-flutter/blob/master/web/auth.html This script is executed after authentication is complete. It sends the authentication result back to the originating window or stores it locally. Ensure this script runs in the context of the redirect page. ```javascript function postAuthenticationMessage() { const message = { 'flutter-web-auth-2': window.location.href }; if (window.opener) { window.opener.postMessage(message, window.location.origin); window.close(); } else if (window.parent && window.parent !== window) { window.parent.postMessage(message, window.location.origin); } else { localStorage.setItem('flutter-web-auth-2', window.location.href); window.close(); } } postAuthenticationMessage(); ``` -------------------------------- ### Set Project ID Environment Variable (Windows CMD) Source: https://github.com/appwrite/playground-for-flutter/blob/master/README.md Sets the PROJECT_ID environment variable for Windows Command Prompt. This is required for subsequent Appwrite CLI commands. ```cmd set PROJECT_ID=playground-for-flutter ``` -------------------------------- ### Standard Compilation Settings Function Source: https://github.com/appwrite/playground-for-flutter/blob/master/windows/CMakeLists.txt A reusable function to apply standard compilation features, options, and definitions to a target, including C++17 support and specific warning/exception settings. ```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() ``` -------------------------------- ### Define list_prepend function in CMake Source: https://github.com/appwrite/playground-for-flutter/blob/master/linux/flutter/CMakeLists.txt This function prepends a prefix to each element in a list. It's used as a workaround for older CMake versions that lack the list(TRANSFORM ... PREPEND ...) command. ```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() ``` -------------------------------- ### Databases: Create Document Source: https://context7.com/appwrite/playground-for-flutter/llms.txt Inserts a new document into an Appwrite collection with specified permissions. Requires database and collection IDs. Permissions can be set for read and write access. ```dart import 'package:appwrite/appwrite.dart'; Future createDocument(Databases databases) async { try { final document = await databases.createDocument( databaseId: ID.custom(databaseId), // 'default' collectionId: ID.custom(collectionId), // 'usernames' documentId: ID.unique(), // auto-generated unique ID data: {'username': 'hello2'}, permissions: [ Permission.read(Role.any()), // anyone can read Permission.write(Role.any()), // anyone can write ], ); print('Document created: ${document.$id}'); print(document.toMap()); // Output: {$id: '...', $collectionId: 'usernames', username: 'hello2', ...} } on AppwriteException catch (e) { print('Create document failed: ${e.message}'); } } ``` -------------------------------- ### Build Type Configuration Source: https://github.com/appwrite/playground-for-flutter/blob/master/linux/CMakeLists.txt Sets the default build type to 'Debug' if not already specified. This ensures a consistent build mode for development unless overridden. ```cmake 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() ``` -------------------------------- ### Native Apple Sign-In for iOS/macOS Source: https://context7.com/appwrite/playground-for-flutter/llms.txt Handles native Apple Sign-In on iOS/macOS by exchanging Apple credentials with an Appwrite Function to create a session. This method is not intended for web platforms. ```dart import 'dart:convert'; import 'dart:io'; import 'package:appwrite/enums.dart'; import 'package:flutter/foundation.dart'; import 'package:sign_in_with_apple/sign_in_with_apple.dart'; Future nativeAppleSignIn(Account account, Functions functions) async { // Only show native button on iOS / macOS (not web) if (kIsWeb || (!Platform.isIOS && !Platform.isMacOS)) return; // 1. Get Apple credential from the OS final credential = await SignInWithApple.getAppleIDCredential( scopes: [ AppleIDAuthorizationScopes.email, AppleIDAuthorizationScopes.fullName, ], ); // 2. Build payload for the Appwrite Function final body = {'code': credential.authorizationCode}; if (credential.givenName?.isNotEmpty ?? false) body['firstName'] = credential.givenName!; if (credential.familyName?.isNotEmpty ?? false) body['lastName'] = credential.familyName!; // 3. Execute the sign-in-with-apple Appwrite Function final execution = await functions.createExecution( functionId: signInWithAppleFunctionId, // 'sign-in-with-apple' method: ExecutionMethod.pOST, headers: {'Content-Type': 'application/json'}, body: jsonEncode(body), ); print('Function status: ${execution.status}'); // 4. Use the returned token to create an Appwrite session final token = json.decode(execution.responseBody) as Map; await account.createSession( userId: token['userId'] as String, secret: token['secret'] as String, ); print('Apple session created for user: ${token['userId']}'); } ``` -------------------------------- ### Flutter Managed Directory Source: https://github.com/appwrite/playground-for-flutter/blob/master/linux/CMakeLists.txt Sets the path to the Flutter managed directory, which contains Flutter-specific build configurations and libraries. This path is relative to the current source directory. ```cmake set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") add_subdirectory(${FLUTTER_MANAGED_DIR}) ```