Amplify has re-imagined the way frontend developers build fullstack applications. Develop and deploy without the hassle.

Page updated Apr 29, 2024

Set up Amplify DataStore

Amplify Flutter v0 is now in Maintenance Mode until July 19th, 2024. This means that we will continue to include updates to ensure compatibility with backend services and security. No new features will be introduced in v0.

Please use the latest version (v1) of Amplify Flutter to get started.

If you are currently using v0, follow these instructions to upgrade to v1.

DataStore with Amplify

Amplify DataStore provides a programming model for leveraging shared and distributed data without writing additional code for offline and online scenarios, which makes working with distributed, cross-user data just as simple as working with local-only data.

Note: this allows you to start persisting data locally to your device with DataStore, even without an AWS account.

Goal

To setup and configure your application with Amplify DataStore and use it to persist data locally on a device.

Prerequisites

As of Amplify Flutter 0.3.0, CLI version >=7.6.10 is required. When updating to 0.3.0, you must re-generate your models with the CLI. You can do so by running amplify codegen models.

  • A Flutter application targeting Flutter SDK >= 2.10.0 (stable version) with Amplify libraries integrated
    • An iOS configuration targeting at least iOS 13.0
    • An Android configuration targeting at least Android API level 21 (Android 5.0) or above
    • For a full example of please follow the project setup walkthrough

Install Amplify Libraries

Add the following dependencies to your pubspec.yaml file and install dependencies when asked:

1environment:
2 sdk: ">=2.15.0 <3.0.0"
3
4dependencies:
5 flutter:
6 sdk: flutter
7
8 amplify_flutter: ^0.6.0
9 amplify_datastore: ^0.6.0

Update The Android Project

Open build.gradle located under android/app, and enable coreLibraryDesugaringEnabled in compileOptions to support the Java8 feature used in the DataStore plugin.

1compileOptions {
2 // add this line to support Java8 features
3 coreLibraryDesugaringEnabled true
4
5 sourceCompatibility JavaVersion.VERSION_1_8
6 targetCompatibility JavaVersion.VERSION_1_8
7}

Add the following dependency in dependencies.

1dependencies {
2 // add this line to support Java8 features
3 coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:1.1.5'
4
5 implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
6}

Setup local development environment

To use Amplify, you must first initialize it for use in your project. If you haven't already done so, run this command:

1amplify init

The base structure for a DataStore app is created by adding a new GraphQL API to your app.

1# For new APIs
2amplify add api
3
4# For existing APIs
5amplify update api

The CLI will prompt you to configure your API. Select GraphQL as the API type and reply to the questions as shown below. Conflict detection is required when using DataStore to sync data with the cloud.

1? Please select from one of the below mentioned services:
2 `GraphQL`
3? Here is the GraphQL API that we will create. Select a setting to edit or continue:
4 `Name`
5? Provide API name:
6 `BlogAppApi`
7? Here is the GraphQL API that we will create. Select a setting to edit or continue:
8 `Authorization modes: API key (default, expiration time: 7 days from now)`
9? Choose the default authorization type for the API
10 `API key`
11? Enter a description for the API key:
12 `BlogAPIKey`
13? After how many days from now the API key should expire (1-365):
14 `365`
15? Configure additional auth types?
16 `No`
17? Here is the GraphQL API that we will create. Select a setting to edit or continue:
18 `Conflict detection (required for DataStore): Disabled`
19? Enable conflict detection?
20 `Yes`
21? Select the default resolution strategy
22 `Auto Merge`
23? Here is the GraphQL API that we will create. Select a setting to edit or continue:
24 `Continue`
25? Choose a schema template
26 `Single object with fields (e.g., “Todo” with ID, name, description)`

Troubleshooting: Cloud sync will fail without the conflict detection configuration. To enable it for an existing project, run amplify update api and choose Enable DataStore for entire API.

Idiomatic persistence

DataStore relies on platform standard data structures to represent the data schema in an idiomatic way. The persistence language is composed by data types that satisfies the Model interface and operations defined by common verbs such as save, query and delete.

Data schema

The first step to create an app backed by a persistent datastore is to define a schema. DataStore uses GraphQL schema files as the definition of the application data model. The schema contains data types and relationships that represent the app's functionality.

Sample schema

For the next steps, let's start with a schema for a small blog application. Currently, it has only a single model. New types and constructs will be added to this base schema as more concepts are presented.

Open the schema.graphql file located by default at amplify/backend/{api_name}/ and define a model Post as follows.

1type Post @model {
2 id: ID!
3 title: String!
4 status: PostStatus!
5 rating: Int
6 content: String
7}
8
9enum PostStatus {
10 ACTIVE
11 INACTIVE
12}

Now you will to convert the platform-agnostic schema.graphql into platform-specific data structures. DataStore relies on code generation to guarantee schemas are correctly converted to platform code.

Like the initial setup, models can be generated either using the IDE integration or Amplify CLI directly.

Code generation: Platform integration

Coming Soon. Please use Amplify CLI for now.

Code generation: Amplify CLI

Models can also be generated using the Amplify CLI directly.

In your terminal, make sure you are in your project/root folder and execute the codegen command:

1amplify codegen models

The generated files will be under the lib/models directory by default. They get re-generated each time codegen is run.

Initialize Amplify DataStore

To initialize the Amplify DataStore, use the Amplify.addPlugin() method to add the AWS DataStore Plugin. You also need to import the codegen dart file ModelProvider.dart. After that, finish configuring Amplify by calling configure():

1import 'package:flutter/material.dart';
2import 'package:amplify_flutter/amplify_flutter.dart';
3import 'package:amplify_datastore/amplify_datastore.dart';
4
5import 'amplifyconfiguration.dart';
6import 'models/ModelProvider.dart';
7
8class MyApp extends StatefulWidget {
9 const MyApp({Key? key}) : super(key: key);
10
11
12 State<MyApp> createState() => _MyAppState();
13}
14
15class _MyAppState extends State<MyApp> {
16
17 void initState() {
18 super.initState();
19 _configureAmplify();
20 }
21
22 Future<void> _configureAmplify() async {
23 // Add the following lines to your app initialization to add the DataStore plugin
24 final datastorePlugin =
25 AmplifyDataStore(modelProvider: ModelProvider.instance);
26 await Amplify.addPlugin(datastorePlugin);
27 try {
28 await Amplify.configure(amplifyconfig);
29 } on AmplifyAlreadyConfiguredException {
30 safePrint(
31 'Tried to reconfigure Amplify; this can occur when your app restarts on Android.');
32 }
33 }
34
35
36 Widget build(BuildContext context) {
37 return const MaterialApp(
38 home: Scaffold(
39 body: SizedBox.shrink(),
40 ),
41 );
42 }
43}

Persistence operations

Now the application is ready to execute persistence operations. The data will be persisted to a local database, enabling offline-first use cases by default.

Even though a GraphQL API is already added to your project, the cloud synchronization will only be enabled when the API plugin is initialized and the backend provisioned. See the Next steps for more info.

Writing to the database

To write to the database, create an instance of the Post model and save it.

1Future<void> savePost() async {
2 final newPost = Post(
3 title: 'New Post being saved',
4 rating: 15,
5 status: PostStatus.INACTIVE,
6 );
7 await Amplify.DataStore.save(newPost);
8}

Reading from the database

To read from the database, the simplest approach is to query for all records of a given model type.

1Future<void> readFromDatabase() async {
2 try {
3 final posts = await Amplify.DataStore.query(Post.classType);
4 print('Posts: $posts');
5 } on DataStoreException catch (e) {
6 print('Query failed: $e');
7 }
8}

Next steps

Congratulations! You’ve created and retrieved data from the local database. Check out the following links to see other Amplify DataStore use cases and advanced concepts: