Set up Amplify DataStore
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.
Goal
To setup and configure your application with Amplify DataStore and use it to persist data locally on a device.
Prerequisites
-
Install and configure Amplify CLI
- An iOS configuration targeting at least iOS 13.0
- An Android configuration targeting at least Android API level 24 (Android 7.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:
dependencies: flutter: sdk: flutter
amplify_datastore: ^1.0.0 amplify_flutter: ^1.0.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.
compileOptions { // add this line to support Java8 features coreLibraryDesugaringEnabled true
sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8}
Add the following dependency in dependencies
.
dependencies { // add this line to support Java8 features coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:1.1.5'
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"}
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:
amplify init
The base structure for a DataStore app is created by adding a new GraphQL API to your app.
# For new APIsamplify add api
# For existing APIsamplify 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.
? Please select from one of the below mentioned services: `GraphQL`? Here is the GraphQL API that we will create. Select a setting to edit or continue: `Name`? Provide API name: `BlogAppApi`? Here is the GraphQL API that we will create. Select a setting to edit or continue: `Authorization modes: API key (default, expiration time: 7 days from now)`? Choose the default authorization type for the API `API key`? Enter a description for the API key: `BlogAPIKey`? After how many days from now the API key should expire (1-365): `365`? Configure additional auth types? `No`? Here is the GraphQL API that we will create. Select a setting to edit or continue: `Conflict detection (required for DataStore): Disabled`? Enable conflict detection? `Yes`? Select the default resolution strategy `Auto Merge`? Here is the GraphQL API that we will create. Select a setting to edit or continue: `Continue`? Choose a schema template `Single object with fields (e.g., “Todo” with ID, name, description)`
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.
type Post @model { id: ID! title: String! status: PostStatus! rating: Int content: String}
enum PostStatus { ACTIVE INACTIVE}
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.
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:
amplify 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()
:
import 'package:flutter/material.dart';import 'package:amplify_flutter/amplify_flutter.dart';import 'package:amplify_datastore/amplify_datastore.dart';
import 'amplifyconfiguration.dart';import 'models/ModelProvider.dart';
class MyApp extends StatefulWidget { const MyApp({Key? key}) : super(key: key);
State<MyApp> createState() => _MyAppState();}
class _MyAppState extends State<MyApp> { void initState() { super.initState(); _configureAmplify(); }
Future<void> _configureAmplify() async { // Add the following lines to your app initialization to add the DataStore plugin final datastorePlugin = AmplifyDataStore(modelProvider: ModelProvider.instance); await Amplify.addPlugin(datastorePlugin); try { await Amplify.configure(amplifyconfig); } on AmplifyAlreadyConfiguredException { safePrint( 'Tried to reconfigure Amplify; this can occur when your app restarts on Android.'); } }
Widget build(BuildContext context) { return const MaterialApp( home: Scaffold( body: SizedBox.shrink(), ), ); }}
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.
import 'package:amplify_flutter/amplify_flutter.dart';
import 'models/ModelProvider.dart';
Future<void> savePost() async { final newPost = Post( title: 'New Post being saved', rating: 15, status: PostStatus.INACTIVE, );
try { await Amplify.DataStore.save(newPost); } on DataStoreException catch (e) { safePrint('Something went wrong saving model: ${e.message}'); }}
Reading from the database
To read from the database, the simplest approach is to query for all records of a given model type.
import 'package:amplify_flutter/amplify_flutter.dart';
import 'models/ModelProvider.dart';
Future<void> queryPosts() async { try { final posts = await Amplify.DataStore.query(Post.classType); safePrint('Posts: $posts'); } on DataStoreException catch (e) { safePrint('Something went wrong querying posts: ${e.message}'); }}
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: