Page updated Jan 16, 2024

Syncing data to cloud

Once you're happy with your application, you can start syncing with the cloud by provisioning a backend from your project. DataStore can connect to remote backend and automatically sync all locally saved data using GraphQL as a data protocol.

Best practice: it is recommended to develop without cloud synchronization enabled initially so you can change the schema as your application takes shape without the impact of having to update the provisioned backend. Once you are satisfied with the stability of your data schema, setup cloud synchronization as described below and the data saved locally will be synchronized to the cloud automatically.

Setup cloud sync

Synchronization between offline and online data can be tricky. DataStore's goal is to remove that burden from the application code and handle all data consistency and reconciliation between local and remote behind the scenes, while developers focus on their application logic. Up to this point the focus was to setup a local data store that works offline and has all the capabilities you would expect from a data persistence framework.

The next step is to make sure the locally saved data is synchronized with a cloud backend powered by AWS AppSync.

Note: Syncing data between the cloud and the local device starts automatically whenever you run any DataStore operation after your app is set up.

Add the API plugin

Although DataStore presents a distinct API, its cloud synchronization functionality relies on the underlying API category. Therefore, you will still be required to incorporate the API plugin when working with DataStore.

Make sure you have the following plugin dependency in your pubspec.yaml.

1amplify_api: ^1.0.0

Locate your Amplify initialization code, and add an AmplifyAPI() plugin. Your initialization code should already include an AmplifyDataStore() plugin from previous steps. Note the new import statement for API towards the top of the file.

Be sure to import your API library first:

1// import the Amplify API plugin
2import 'package:amplify_api/amplify_api.dart';
3import 'package:amplify_datastore/amplify_datastore.dart';
4import 'package:amplify_flutter/amplify_flutter.dart';
5
6import 'amplifyconfiguration.dart';
7import 'models/ModelProvider.dart';

Then update your configuration function, in this example it is _configureAmplify function, by adding AmplifyAPI like mentioned:

1void _configureAmplify() async {
2 final datastorePlugin = AmplifyDataStore(
3 modelProvider: ModelProvider.instance,
4 );
5 // Add the following line and update your function call with `addPlugins`
6 final api = AmplifyAPI();
7 await Amplify.addPlugins([datastorePlugin, api]);
8 try {
9 await Amplify.configure(amplifyconfig);
10 } on AmplifyAlreadyConfiguredException {
11 print('Tried to reconfigure Amplify; this can occur when your app restarts on Android.');
12 }
13}

Push the backend to the cloud

By now you should have a backend created with conflict detection enabled, as described in the Getting started guide.

Check the status of the backend to verify if it is already provisioned in the cloud.

1amplify status

You should see a table similar to this one.

1| Category | Resource name | Operation | Provider plugin |
2| -------- | ----------------- | --------- | ----------------- |
3| Api | amplifyDatasource | No Change | awscloudformation |

Troubleshooting: if amplify status gives you an error saying "You are not working inside a valid Amplify project", make sure you run amplify init before the next step.

In case Operation says Create or Update you need to push the backend to the cloud.

1amplify push

AWS credentials needed. At this point an AWS account is required. If you have never run amplify configure before, do it so and follow the steps to configure Amplify with your AWS account. Details can be found in the Configure the Amplify CLI guide.

Existing backend

DataStore can connect to an existing AWS AppSync backend that has been deployed from another project, no matter the platform it was originally created in. In these workflows it is best to work with the CLI directly by running an amplify pull command from your terminal and then generating models afterwards, using the process described in the Getting started guide.

For more information on this workflow please see the Multiple Frontends documentation.

Distributed data

When working with distributed data, it is important to be mindful about the state of the local and the remote systems. DataStore tries to make that as simple as possible for you; however, some scenarios might require some consideration.

For instance, when updating or deleting data, one has to consider that the state of the local data might be out-of-sync with the backend. This scenario can affect how conditions should be implemented.

Update and delete with predicate

For such scenarios both the save() and the delete() APIs support an optional predicate which will be sent to the backend and executed against the remote state.

1import 'package:amplify_flutter/amplify_flutter.dart';
2
3import 'models/ModelProvider.dart';
4
5Future<void> savePredicate(Post post) async {
6 final post = ...; // get post using the query API
7 final updatedPost = post.copyWith(title: '[Amplified]');
8 try {
9 // if the post title has changed to something else other than
10 // a string that starts with "[Amplify]", the save will be rejected
11 await Amplify.DataStore.save(
12 updatedPost,
13 where: Post.TITLE.beginsWith("[Amplify]"),
14 );
15 } on DataStoreException {
16 safePrint('Could not update post, maybe the title has been changed?');
17 }
18}

There's a difference between the traditional local condition check using if/else constructs and the predicate in the save() and delete() APIs as you can see in the example below.

1// Tests only against the local state
2Future<void> savePredicateLocally(Post post) async {
3 if (post.title.startsWith('[Amplify]')) {
4 await Amplify.DataStore.save(post);
5 }
6}
7
8// Only applies the update if the data in the remote backend satisfies the criteria
9Future<void> savePredicateRemotely(Post post) async {
10 try {
11 await Amplify.DataStore.save(
12 post,
13 where: Post.TITLE.beginsWith('[Amplify]'),
14 );
15 } on DataStoreException catch (e) {
16 ...
17 }
18}

Conflict detection and resolution

When concurrently updating the data in multiple places, it is likely that some conflict might happen. For most of the cases the default Auto-merge algorithm should be able to resolve conflicts. However, there are scenarios where the algorithm won't be able to be resolved, and in these cases, a more advanced option is available and will be described in detail in the conflict resolution section.

Clear local data

Amplify.DataStore.clear() provides a way for you to clear all local data if needed. This is a destructive operation but the remote data will remain intact. When the next sync happens, data will be pulled into the local storage again and reconstruct the local data.

One common use for clear() is to manage different users sharing the same device or even as a development-time utility.

Note: In case multiple users share the same device and your schema defines user-specific data, make sure you call Amplify.DataStore.clear() when switching users. Visit Auth events for all authentication related events.

1import 'dart:async';
2
3import 'package:amplify_flutter/amplify_flutter.dart';
4
5final hubSubscription =
6 Amplify.Hub.listen(HubChannel.Auth, (AuthHubEvent hubEvent) async {
7 if (hubEvent.eventName == 'SIGNED_OUT') {
8 try {
9 await Amplify.DataStore.clear();
10 safePrint('DataStore is cleared as the user has signed out.');
11 } on DataStoreException catch (e) {
12 safePrint('Failed to clear DataStore: $e');
13 }
14 }
15});

This is a simple yet effective example. However, in a real scenario you might want to only call clear() when a different user is signedIn in order to avoid clearing the database for a repeated sign-in of the same user.

Selectively syncing a subset of your data

By default, DataStore fetches all the records that you’re authorized to access from your cloud data source to your local device. The maximum number of records that will be stored locally is configurable here.

You can utilize selective sync to persist a subset of your data instead.

Selective sync works by applying predicates to the base and delta sync queries, as well as to incoming subscriptions.

Note that selective sync is applied on top of authorization rules you’ve defined on your schema with the @auth directive. For more information see the Setup authorization rules section.

1void _configureAmplify() async {
2 // Update AmplifyDataStore instance like below
3 final datastorePlugin = AmplifyDataStore(
4 modelProvider: ModelProvider.instance,
5 syncExpressions: [
6 DataStoreSyncExpression(Post.classType, () => Post.RATING.gt(5)),
7 DataStoreSyncExpression(
8 Comment.classType,
9 () => Comment.POST.beginsWith('This'),
10 )
11 ],
12 );
13 ...
14}

When DataStore starts syncing, only Posts with rating > 5 and Comments with POST id begins with "This" will be synced down to the user's local store.

Developers should only specify a single syncExpression per model. Any subsequent expressions for the same model will be ignored.

Reevaluate expressions at runtime

Sync expressions get evaluated whenever DataStore starts. In order to have your expressions reevaluated, you can execute Amplify.DataStore.clear() or Amplify.DataStore.stop() followed by Amplify.DataStore.start().

If you have the following expression and you want to change the filter that gets applied at runtime, you can do the following:

1int rating = 5;
2
3Future<void> initialize() async {
4 final dataStorePlugin = AmplifyDataStore(
5 modelProvider: ModelProvider.instance,
6 syncExpressions: [
7 DataStoreSyncExpression(
8 Post.classType,
9 () => Post.RATING.gt(rating),
10 ),
11 ],
12 );
13
14 await Amplify.addPlugin(dataStorePlugin);
15}
16
17Future<void> changeSync() async {
18 rating = 1;
19 try {
20 await Amplify.DataStore.stop();
21 } catch(error) {
22 print('Error stopping DataStore: $error');
23 }
24
25 try {
26 await Amplify.DataStore.start();
27 } on Exception catch (error) {
28 print('Error starting DataStore: $error');
29 }
30}

Each time DataStore starts (via start or any other operation: query, save, delete, or observe), DataStore will reevaluate the syncExpressions.

In the above case, the predicate will contain the value 1, so all Posts with rating > 1 will get synced down.

Keep in mind: Amplify.DataStore.stop() will retain the local store's existing content. Run Amplify.DataStore.clear() to clear the locally-stored contents.

When applying a more restrictive filter, clear the local records first by running DataStore.clear() instead:

1Future<void> changeSync() async {
2 rating = 8;
3 try {
4 await Amplify.DataStore.clear();
5 } on Exception catch (error) {
6 print('Error clearing DataStore: $error');
7 }
8
9 try {
10 await Amplify.DataStore.start();
11 } on Exception catch (error) {
12 print('Error starting DataStore: $error');
13 }
14}

This will clear the contents of your local store, reevaluate your sync expressions and re-sync the data from the cloud, applying all of the specified predicates to the sync queries.

You can also have your sync expression return QueryPredicateConstant.all in order to remove any filtering for that model. This will have the same effect as the default sync behavior.

1int rating = 5;
2
3Future<void> initialize() async {
4 var dataStorePlugin = AmplifyDataStore(
5 modelProvider: ModelProvider.instance,
6 syncExpressions: [
7 DataStoreSyncExpression(
8 Post.classType,
9 () {
10 if (rating > 0) {
11 return QueryPredicate.all;
12 }
13
14 return Post.RATING.gt(rating);
15 },
16 ),
17 ],
18 );
19
20 await Amplify.addPlugin(dataStorePlugin);
21}

DataStore.configure() should only by called once.

Advanced use case - Query instead of Scan

By default, Datastore sync performs a Scan on DynamoDB tables, which is less efficient when a table contains a large set of data. You can use syncExpression when configuring Datastore to filter synced data to improve performance using Query rather than Scan.

You can enable Query during the sync by following the below steps:

  1. Create a Global Secondary Index (GSI) for your schema, e.g. in the below schema a GSI will be created using field lastName as the GSI primary key, and createdAt as the GSI sort key. Learn about creating GSIs with the @index directive here.
1type User @model {
2 id: ID!
3 firstName: String!
4 lastName: String! @index(name: "byLastName", sortKeyFields: ["createdAt"])
5 createdAt: AWSDateTime!
6}
  1. Configure DataStore with syncExpression returning a predicate that maps to a query expression.

To construct a query expression, return a predicate with the primary key of the GSI. You can only use the eq operator with this predicate.

For the schema defined above User.LASTNAME.eq("Doe") is a valid query expression.

Optionally, you can also chain the sort key to this expression, using any of the following operators: eq | ne | le | lt | ge | gt | beginsWith | between.

E.g., User.LASTNAME.eq("Doe").and(User.CREATEDAT.gt("2020-10-10")).

Both of these sync expressions will result in AWS AppSync retrieving records from Amazon DynamoDB via a query operation:

1Future<void> initializeSingleEquals() async {
2 // Using eq operator with the primary key of the GSI
3 final singleEqualsStore = AmplifyDataStore(
4 modelProvider: ModelProvider.instance,
5 syncExpressions: [
6 DataStoreSyncExpression(
7 User.classType,
8 () => User.LASTNAME.eq("Doe"),
9 ),
10 ],
11 );
12
13 await Amplify.addPlugin(singleEqualsStore);
14}
15
16Future<void> initializeChainedEquals() async {
17 // Using eq operator with the primary key of the GSI and
18 // chaining the gt operator with the sort key
19 final chainedEqualGtStore = AmplifyDataStore(
20 modelProvider: ModelProvider.instance,
21 syncExpressions: [
22 DataStoreSyncExpression(
23 User.classType,
24 () => User.LASTNAME.eq("Doe").and(User.CREATEDAT.gt("2020-10-10")),
25 ),
26 ],
27 );
28
29 await Amplify.addPlugin(chainedEqualGtStore);
30}