Appwrite Flutter SDK

repository·main·Indexed 19 days ago

https://github.com/appwrite/sdk-for-flutter

A high-level Dart API for Flutter applications to interact with the Appwrite Backend-as-a-Service (BaaS). The SDK enables management of authentication via the Account class, databases, and storage. It is compatible with Appwrite server version 1.9.x and supports Android, iOS, macOS, Web, Windows, and Linux platforms.

Tokens
62.7K
Snippets
212
Records
222
Agent score
65%

What's inside appwrite-sdk-for-flutter

  1. Configure Android for Appwrite

    main

    To allow your Android app to communicate with the Appwrite API and handle OAuth callbacks, you must add a specific activity to your AndroidManifest.xml inside the <application> tag.

    Replace [PROJECT_ID] with your actual Appwrite Project ID found in your project settings.

    <manifest ...>
        <application ...>
            <!-- Add this inside the <application> tag, alongside the existing <activity> tags -->
            <activity android:exported="true" android:name="com.linusu.flutter_web_auth_2.CallbackActivity" >
                <intent-filter android:label="flutter_web_auth_2">
                    <action android:name="android.intent.action.VIEW" />
                    <category android:name="android.intent.category.DEFAULT" />
                    <category android:name="android.intent.category.BROWSABLE" />
                    <data android:scheme="appwrite-callback-[PROJECT_ID]" />
                </intent-filter>
            </activity>
        </application>
    </manifest>
  2. Configure Web for Appwrite

    main

    To support Flutter Web and OAuth2 callbacks, follow these steps:

    1. Register Domain: In the Appwrite Console, add your web platform and list the domain your website will use.
    2. Create Callback HTML: Create an HTML file (e.g., ./web/auth.html) to handle the postMessage() callback from the authentication window.
    3. Match URLs: The redirection URL used in your authentication service must match your application's running URL (schema, host, port) and point to the path of your created HTML file (e.g., /auth.html).

    Important: For cross-domain communication, ensure your Appwrite server and Flutter client use the same top-level domain and protocol (HTTP or HTTPS) to avoid 401 errors caused by browser cookie restrictions.

    <!DOCTYPE html>
    <title>Authentication complete</title>
    <p>Authentication is complete. If this does not happen automatically, please close the window.</p>
    <script>
      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();
    </script>
  3. Initialize the Appwrite Client

    main

    Initialize the Client object with your Project ID. If you are using a self-hosted Appwrite instance, you must also call .setEndpoint().

    Note for Emulators: When connecting to a local Appwrite instance from an Android or iOS emulator, do not use localhost. Use your machine's private IP address (e.g., 192.168.1.100) so the device can reach the host machine.

    Client client = Client().setProject('<YOUR_PROJECT_ID>').setEndpoint('https://your-endpoint.com');
  4. Install the Appwrite Flutter SDK

    main

    To use Appwrite in your Flutter project, add the appwrite package to your pubspec.yaml dependencies or use the Flutter CLI.

    Note: This SDK is compatible with Appwrite server version 1.9.x.

    dependencies:
      appwrite: ^25.4.0
    flutter pub add appwrite
  5. Configure Appwrite Platforms

    main

    Before using the SDK, you must register your Flutter application in the Appwrite Console.

    1. Go to your Appwrite project in the console.
    2. Click 'Add Platform'.
    3. Select 'Flutter'.
    4. Enter your app's credentials (Name and Package Name/Bundle ID).

    You must repeat this process for every platform you intend to support (Android, iOS, Linux, macOS, Web, and Windows).

  6. Initialize the Appwrite SDK

    main

    To use Appwrite in your Flutter application, you must first initialize a Client object by providing your API endpoint and your project ID. This client instance is then passed to specific service classes (like Organization) to perform operations.

    import 'package:appwrite/appwrite.dart';
    
    Client client = Client()
        .setEndpoint('https://<REGION>.cloud.appwrite.io/v1') // Your API Endpoint
        .setProject('<YOUR_PROJECT_ID>'); // Your project ID
  7. Configure iOS and macOS for Appwrite

    main

    The SDK uses ASWebAuthenticationSession for OAuth. You must ensure your deployment targets are high enough:

    iOS:

    • Set the iOS Deployment Target to iOS 11.0 or higher in Xcode (Runner target > General tab).
    • Add your app's Bundle ID in the Appwrite Console.

    macOS:

    • Set the macOS Deployment Target to macOS 10.15 or higher in Xcode.
    • Add your app's Bundle ID in the Appwrite Console.
  8. Initialize the Appwrite Client and Organization service

    main

    To use the Organization service, you must first initialize a Client with your Appwrite endpoint and project ID. Once the client is configured, you can instantiate the Organization class by passing the client instance to its constructor.

    Ensure you replace <REGION> with your specific Appwrite Cloud region and provide your actual <YOUR_PROJECT_ID>.

    import 'package:appwrite/appwrite.dart';
    
    Client client = Client()
        .setEndpoint('https://<REGION>.cloud.appwrite.io/v1') // Your API Endpoint
        .setProject('<YOUR_PROJECT_ID>'); // Your project ID
    
    Organization organization = Organization(client);
  9. Manage files with the Storage service

    main

    The Storage service allows you to manage project files within Appwrite buckets. You can upload files, list files, retrieve file metadata, update file details, delete files, and handle file downloads or previews.

    Note: Before uploading files, you must ensure a bucket exists, either via the Appwrite Console or the Server SDK.

    final storage = storage(client);
  10. Manage user accounts with the Account service

    main

    The Account service is used to authenticate users, manage their profiles, and handle sessions. It provides methods for registration, login, profile updates (email, password, name, phone, preferences), and Multi-Factor Authentication (MFA).

    // Example initialization (assuming client is already configured)
    final account = Account(client);
  11. Understand the Execution model

    main

    The Execution class represents the result and metadata of an Appwrite Function execution. It provides details about how the function was triggered, its current status, the HTTP request/response details (if applicable), and execution logs or errors.

    Key Properties

    • Metadata: $id, $createdAt, $updatedAt, and $permissions.
    • Function Context: functionId, deploymentId, and the trigger (e.g., http, schedule, or event).
    • Status: The current status of the execution (e.g., waiting, processing, completed, failed, or scheduled).
    • HTTP Details: For synchronous executions, you can access requestMethod, requestPath, requestHeaders, responseStatusCode, responseBody, and responseHeaders.
    • Diagnostics: logs and errors contain the last 4,000 characters of execution output. Note that these may be empty unless the response is retrieved via an API key or a webhook payload.
    • Performance: duration provides the execution time in seconds.
    • Scheduling: scheduledAt indicates when the execution was set to run.
    // Example of accessing Execution properties
    void handleExecution(Execution execution) {
      print('Execution ID: ${execution.$id}');
      print('Status: ${execution.status}');
      print('Duration: ${execution.duration}s');
      
      if (execution.status == enums.ExecutionStatus.failed) {
        print('Error: ${execution.errors}');
      }
    }
  12. Filter and search data with the Query class

    main

    The Query class provides a set of static methods to generate query strings used for filtering, searching, sorting, and paginating data in Appwrite. These queries are typically passed as a list of strings to service methods like databases.listDocuments().

    Common Query Types

    Comparison and Logic

    • equal(attribute, value): Matches where attribute equals value. If value is a list, it matches any value in that list.
    • notEqual(attribute, value): Matches where attribute is not equal to value.
    • lessThan(attribute, value), lessThanEqual(attribute, value), greaterThan(attribute, value), greaterThanEqual(attribute, value): Standard numeric/date comparisons.
    • between(attribute, start, end): Matches where attribute is between start and end (inclusive).
    • regex(attribute, pattern): Matches using a regular expression.
    • or([queries]) and and([queries]): Logical grouping of multiple query strings.

    String and Array Operations

    • startsWith(attribute, value) / endsWith(attribute, value) / contains(attribute, value): String pattern matching.
    • exists(attributes) / notExists(attributes): Checks for the presence of specific attributes.
    • containsAny(attribute, values): For arrays/relationships, matches if the attribute contains at least one of the values.
    • containsAll(attribute, values): For arrays/relationships, matches if the attribute contains all of the values.
    • elemMatch(attribute, queries): Filters array elements where at least one element matches all specified queries.

    Metadata and System Queries

    Appwrite provides built-in attributes for system metadata:

    • createdBefore(value), createdAfter(value), createdBetween(start, end): Filters by $createdAt.
    • updatedBefore(value), updatedAfter(value), updatedBetween(start, end): Filters by $updatedAt.

    Sorting and Pagination

    • orderAsc(attribute) / orderDesc(attribute): Sorts results.
    • limit(int): Limits the number of returned results.
    • offset(int): Skips a specific number of results.
    • cursorBefore(id) / cursorAfter(id): Used for cursor-based pagination.
    • distanceEqual, distanceGreaterThan, etc.: Filters based on distance from coordinates.
    • vectorDot, vectorCosine, vectorEuclidean: Performs vector similarity searches.
    • intersects, crosses, overlaps, touches: Geometric intersection queries.
    // Example: Fetching documents that are active and were created after a certain date
    final documents = await databases.listDocuments(
      databaseId: 'my_db',
      collectionId: 'my_collection',
      queries: [
        Query.equal('status', 'active'),
        Query.createdAfter('2023-01-01T00:00:00.000Z'),
        Query.orderDesc('$createdAt'),
        Query.limit(25),
      ],
    );