appwrite 27.1.0-rc.7 copy "appwrite: ^27.1.0-rc.7" to clipboard
appwrite: ^27.1.0-rc.7 copied to clipboard

Appwrite is an open-source self-hosted backend server that abstracts and simplifies complex and repetitive development tasks behind a very simple REST API

Appwrite Flutter SDK #

pub package License Version Build Status Twitter Account Discord

This SDK targets Appwrite server version 2.3.x as shipped on Appwrite Cloud. Self-hosted releases can lag behind Cloud — if you run an older self-hosted build, use a matching older SDK from previous releases when APIs differ.

Appwrite is an open-source backend as a service server that abstracts and simplifies complex and repetitive development tasks behind a very simple to use REST API. Appwrite aims to help you develop your apps faster and in a more secure way. Use the Flutter SDK to integrate your app with the Appwrite server to easily start interacting with all of Appwrite backend APIs and tools. For full API documentation and tutorials go to https://appwrite.io/docs

Appwrite

Installation #

Add this to your package's pubspec.yaml file:

dependencies:
  appwrite: ^27.1.0-rc.7

You can install packages from the command line:

flutter pub add appwrite

Push on Android #

Push includes a native Android plugin, so the SDK needs Android 7.0 (API 24) or later: apps with a lower minSdk fail to build until they raise it. flutter_local_notifications also needs core library desugaring. Add both to android/app/build.gradle.kts (desugaring is configured when the app is assembled, so a plugin cannot apply it for you):

android {
    defaultConfig {
        minSdk = 24
    }
    compileOptions {
        isCoreLibraryDesugaringEnabled = true
    }
}

dependencies {
    coreLibraryDesugaring("com.android.tools:desugar_jdk_libs:2.1.4")
}

A subscription with background: true keeps delivering after the app is backgrounded, killed or the device restarts, until it is unsubscribed or push.close() is called (do this on sign-out). The plugin saves the subscription, and a scheduled job and alarm wake the app every 15 to 60 seconds to reconnect; the broker replays what was sent in between (retry: true). While the app is not on screen, each message is posted as a notification that opens the app. It reconnects with the credential saved at subscribe time, so use a session rather than a short-lived JWT.

On Android 13 and later, the first background subscription asks the user for the POST_NOTIFICATIONS runtime permission. If they decline, the subscription still delivers to your callback but posts no notification. Notifications show the title, body and image sent with createPush, and fall back to the subscription's title and the raw payload for other messages.

Notifications are posted while the app is backgrounded or closed. While it is on screen your callback shows the message, so none is posted unless the subscription passes notifyInForeground: true.

final sub = await push.subscribe('news', (message) => print(message.data),
    background: true, title: 'News');

// Optional: immediate delivery even after a kill and during Doze, with a quiet ongoing
// notification (call while the app is in the foreground).
await push.setForeground(true);

Foreground mode runs a remoteMessaging foreground service, which Google Play asks apps to declare in the Play Console. Apps that never enable it can remove the service from their merged manifest with tools:node="remove" on io.appwrite.services.PushService and android.permission.FOREGROUND_SERVICE_REMOTE_MESSAGING.

Delivery while the app is closed

Messages sent while the app is closed arrive at the next scheduled wake-up. While the device is awake that is about every 15 seconds, or about every 60 seconds once exact alarms are allowed; without exact alarms the wake-ups are inexact, so battery saver can defer them further. In Doze (screen off and idle for a while) Android limits background alarms, exact ones included, to about one every nine minutes, so a closed app can take several minutes to receive a message: allowing exact alarms makes wake-ups punctual, it does not lift Doze. For immediate delivery, also in Doze, use push.setForeground(true) (see above).

The SDK uses exact alarms on its own whenever the app may schedule them. To allow it:

  1. Declare the permissions in your app's AndroidManifest.xml. Both are optional and subject to Google Play policy: SCHEDULE_EXACT_ALARM needs a declaration in the Play Console, and USE_EXACT_ALARM is reserved for alarm, clock and calendar apps (the SDK does not use it).

    <uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />
    <uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
    
  2. On Android 13 and later the user has to allow exact alarms, under Settings > Apps > Special app access > Alarms & reminders. Android 12 grants a declared SCHEDULE_EXACT_ALARM automatically, and older versions need nothing. Check with await push.backgroundStatus(): when bestEffort is true, explain why to the user, then from a user action open that screen with push.requestExactAlarms(), or ask for the battery-optimisation exemption with push.requestIgnoreBatteryOptimizations(). Both return false when there is nothing to ask, including when the permission is not declared. The SDK never opens these screens on its own.

If the user force-stops the app (Settings > Force stop, and on some devices swiping it away from recents), Android cancels its alarms and jobs: nothing is delivered until the app is opened again, and the broker then replays what was sent meanwhile.

Set the notification icon with <meta-data android:name="io.appwrite.push.notification_icon" android:resource="@drawable/..." /> in your <application>; without it a generic icon is used.

Opening a tapped notification #

Read the data sent with createPush when the user taps a background notification:

// The tap that launched the app (reported once, so call it at startup).
final opened = await push.getInitialNotification();
if (opened != null) openSale(opened.data['saleId']);

// Taps while the app is running, including in the background.
final stop = push.onNotificationOpened((opened) => openSale(opened.data['saleId']));

On Android the SDK's native plugin reports the taps, on iOS flutter_local_notifications, and on the web the notification's click while the page is open.

Getting Started #

Add your Flutter Platform #

To init your SDK and start interacting with Appwrite services, you need to add a new Flutter platform to your project. To add a new platform, go to your Appwrite console, choose the project you created in the step before, and click the 'Add Platform' button.

From the options, choose to add a new Flutter platform and add your app credentials. Appwrite Flutter SDK currently supports building apps for Android, iOS, Linux, Mac OS, Web and Windows.

If you are building your Flutter application for multiple devices, you have to follow this process for each different device.

On Android, iOS and macOS, call createOAuth2Session without the success and failure URLs. The SDK only returns to your app through the appwrite-callback-[PROJECT_ID] scheme, and only the default redirect carries the new session with it. A custom URL, such as an https App Link, makes the call fail (for example with PlatformException(CANCELED)) even when the login itself succeeded. Await the returned Future and navigate from your Dart code instead.

Android #

For Android first add your app and , Your package name is generally the applicationId in your app-level build.gradle file. By registering your new app platform, you are allowing your app to communicate with the Appwrite API.

In order to capture the Appwrite OAuth callback url, the following activity needs to be added inside the <application> tag, along side the existing <activity> tags in your AndroidManifest.xml. Be sure to replace the [PROJECT_ID] string with your actual Appwrite project ID. You can find your Appwrite project ID in your project settings screen in the console.

<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>

iOS #

For iOS first add your app name and Bundle ID, You can find your Bundle Identifier in the General tab for your app's primary target in Xcode.

The Appwrite SDK uses ASWebAuthenticationSession on iOS 12+ and SFAuthenticationSession on iOS 11 to allow OAuth authentication. You have to change your iOS Deployment Target in Xcode to be iOS >= 11 to be able to build your app on an emulator or a real device.

  1. In Xcode, open Runner.xcworkspace in your app's ios folder.
  2. To view your app's settings, select the Runner project in the Xcode project navigator. Then, in the main view sidebar, select the Runner target.
  3. Select the General tab.
  4. In Deployment Info, 'Target' select iOS 11.0

Linux #

For Linux add your app and , Your package name is generally the name in your pubspec.yaml file. If you cannot find the correct package name, run the application in linux, and make any request with proper exception handling, you should get the application ID needed to add in the received error message.

macOS #

For macOS add your app name and Bundle ID, You can find your Bundle Identifier in the General tab for your app's primary target in Xcode.

The Appwrite SDK uses ASWebAuthenticationSession on macOS 10.15+ to allow OAuth authentication. You have to change your macOS Deployment Target in Xcode to be macOS >= 10.15 to be able to build your app for macOS.

Web #

Appwrite 0.7, and the Appwrite Flutter SDK 0.3.0 have added support for Flutter Web. To build web apps that integrate with Appwrite successfully, all you have to do is add a web platform on your Appwrite project's dashboard and list the domain your website will use to allow communication to the Appwrite API.

For web in order to capture the OAuth2 callback URL and send it to the application using JavaScript postMessage(), you need to create an html file inside ./web folder of your Flutter project. For example auth.html with the following content.

<!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>

Redirection URL passed to the authentication service must be the same as the URL on which the application is running (schema, host, port if necessary) and the path must point to created HTML file, /auth.html in this case. The callbackUrlScheme parameter of the authenticate() method does not take into account, so it is possible to use a schema for native platforms in the code.

Flutter Web Cross-Domain Communication & Cookies

While running Flutter Web, make sure your Appwrite server and your Flutter client are using the same top-level domain and the same protocol (HTTP or HTTPS) to communicate. When trying to communicate between different domains or protocols, you may receive HTTP status error 401 because some modern browsers block cross-site or insecure cookies for enhanced privacy. In production, Appwrite allows you set multiple custom-domains for each project.

Windows #

For Windows add your app and , Your package name is generally the name in your pubspec.yaml file. If you cannot find the correct package name, run the application in windows, and make any request with proper exception handling, you should get the application id needed to add in the received error message.

Init your SDK #

Initialize your SDK with your project ID, which can be found in your project settings page.

Client client = Client().setProject('<YOUR_PROJECT_ID>');

If using a self-hosted instance, you will also need to set your Appwrite endpoint using the setEndpoint method. Before starting to send any API calls to your new Appwrite instance, make sure your Android or iOS emulators has network access to the Appwrite server hostname or IP address. When trying to connect to a local Appwrite instance from an emulator or a mobile device, localhost is the hostname for the device or emulator and not your machine. You should replace localhost with your machine's private IP as the Appwrite endpoint's hostname (e.g. 192.168.1.100). You can also use a service like ngrok to proxy the Appwrite API.

Make Your First Request #

Once your SDK object is set, access any of the Appwrite services and choose any request to send. Full documentation for any service method you would like to use can be found in your SDK documentation or in the [API References](https://appwrite.io/docs) section.

Account account = Account(client);

User user = await account.create(
  userId: ID.unique(),
  email: 'email@example.com',
  password: 'password',
  name: 'Walter O'Brien',
);

Full Example #

Client client = Client().setProject('<YOUR_PROJECT_ID>>');

Account account = Account(client);

User user = await account.create(
  userId: ID.unique(),
  email: 'email@example.com',
  password: 'password',
  name: 'Walter O'Brien'
);

Error Handling #

The Appwrite Flutter SDK raises AppwriteException object with message, type, code and response properties. You can handle any errors by catching AppwriteException and present the message to the user or handle it yourself based on the provided error information. Below is an example.

try {
  User user = await account.create(...);
} on AppwriteException catch(e) {
  // Handle the exception
}

Learn more #

You can use the following resources to learn more and get help

Contribution #

This library is auto-generated by Appwrite custom SDK Generator. To learn more about how you can help us improve this SDK, please check the contribution guide before sending a pull-request.

License #

Please see the BSD-3-Clause license file for more information.

581
likes
100
points
15.8k
downloads

Documentation

Documentation
API reference

Publisher

verified publisherappwrite.io

Weekly Downloads

Appwrite is an open-source self-hosted backend server that abstracts and simplifies complex and repetitive development tasks behind a very simple REST API

Homepage
Repository (GitHub)
View/report issues

License

BSD-3-Clause (license)

Dependencies

cookie_jar, device_info_plus, flutter, flutter_background_service, flutter_local_notifications, flutter_web_auth_2, http, mqtt5_client, package_info_plus, path_provider, typed_data, web, web_socket_channel

More

Packages that depend on appwrite

Packages that implement appwrite