Manipulating data
Create and update
To write data to the DataStore, pass an instance of a model to Amplify.DataStore.save()
:
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}'); }}
The save
method creates a new record, or in the event that one already exists in the local store, it updates the record.
import 'package:amplify_flutter/amplify_flutter.dart';
import 'models/ModelProvider.dart';
Future<void> updatePost() async { final oldPost = (await Amplify.DataStore.query( Post.classType, where: Post.ID.eq('123'), )) .first;
final newPost = oldPost.copyWith(title: 'Updated Title');
try { await Amplify.DataStore.save(newPost); } on DataStoreException catch (e) { safePrint('Something went wrong updating model: ${e.message}'); }}
class MyApp extends StatefulWidget { const MyApp({Key? key}) : super(key: key);
State<MyApp> createState() => _MyAppState();}
class _MyAppState extends State<MyApp> { StreamSubscription<QuerySnapshot<Post>>? _stream;
// A reference to the retrieved post late Post _post;
void initState() { super.initState(); _configure(); }
// Initialize the Amplify libraries and call `observeQuery` Future<void> _configure() async { // ... } ...
void observeQuery() { _stream = Amplify.DataStore.observeQuery( Post.classType, where: Post.ID.eq('123') ).listen((QuerySnapshot<Post> snapshot) { setState(() { _post = snapshot.items.first; }); }); }
Future<void> updatePost(String newTitle) async { final updatedPost = _post.copyWith(title: newTitle); await Amplify.DataStore.save(updatedPost);
// you do not need to explicitly set _post here; observeQuery will see // the update and set the variable. }
// Build function and UI elements ...
void dispose() { _stream?.cancel(); super.dispose(); }}
Delete
To delete an item, simply pass in an instance.
Below, you query for an instance with an id
of 123
, and then delete it, if found:
import 'package:amplify_flutter/amplify_flutter.dart';
import 'models/ModelProvider.dart';
Future<void> deletePostsWithId() async { final postToDelete = (await Amplify.DataStore.query( Post.classType, where: Post.ID.eq('123'), )) .first;
try { await Amplify.DataStore.delete(postToDelete); } on DataStoreException catch (e) { safePrint('Something went wrong deleting model: ${e.message}'); }}
Query Data
Queries are performed against the local store. When cloud synchronization is enabled, the local store is updated in the background by the DataStore Sync Engine.
For more advanced filtering, such as matching arbitrary field values on an object, you can supply a query predicate.
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}'); }}
Predicates
Predicates are filters that can be used to match items in the DataStore. When applied to a query(), they constrain the returned results. When applied to a save(), they act as a pre-requisite for updating the data. You can match against fields in your schema by using the following predicates:
Strings: eq | ne | le | lt | ge | gt | contains | beginsWith | between
Numbers: eq | ne | le | lt | ge | gt | between
Lists: contains
For example if you wanted a list of all Post
Models that have a rating
greater than 4:
import 'package:amplify_flutter/amplify_flutter.dart';
import 'models/ModelProvider.dart';
Future<void> queryPostsWithRatingGreaterThanFour() async { try { final posts = await Amplify.DataStore.query( Post.classType, where: Post.RATING.ge(4), ); safePrint('Posts that have a rating > 4: $posts'); } on DataStoreException catch (e) { safePrint('Something went wrong querying posts: ${e.message}'); }}
Multiple conditions can also be used, like the ones defined in GraphQL Transform condition statements. For example, fetch all posts that have a rating greater than 4
and are ACTIVE
:
import 'package:amplify_flutter/amplify_flutter.dart';
import 'models/ModelProvider.dart';
Future<void> queryPublishedPostsWithRatingFour() async { try { final posts = await Amplify.DataStore.query( Post.classType, where: Post.RATING.eq(4).and(Post.STATUS.eq(PostStatus.ACTIVE)), ); safePrint('Published posts that have a rating 4: $posts'); } on DataStoreException catch (e) { safePrint('Something went wrong querying posts: ${e.message}'); }}
Alternatively, the or
logical operator can also be used:
import 'package:amplify_flutter/amplify_flutter.dart';
import 'models/ModelProvider.dart';
Future<void> queryPublishedOrWithRatingTwoPosts() async { try { final posts = await Amplify.DataStore.query( Post.classType, where: Post.RATING.eq(2).or(Post.STATUS.eq(PostStatus.ACTIVE)), ); safePrint('Posts that are published, or have a rating 2: $posts'); } on DataStoreException catch (e) { safePrint('Something went wrong querying posts: ${e.message}'); }}
Sort
Query results can also be sorted by one or more fields.
For example, to sort all Post
objects by rating
in ascending order:
import 'package:amplify_flutter/amplify_flutter.dart';
import 'models/ModelProvider.dart';
Future<void> queryPostsInAscendingOrderByRating() async { try { final posts = await Amplify.DataStore.query( Post.classType, sortBy: [Post.RATING.ascending()], ); safePrint('Posts: $posts'); } on DataStoreException catch (e) { safePrint('Something went wrong querying posts: ${e.message}'); }}
To get all Post
objects sorted first by rating
in ascending order, and then by title
in descending order:
import 'package:amplify_flutter/amplify_flutter.dart';
import 'models/ModelProvider.dart';
Future<void> queryPostsFirstInAscendingRatingOrderThenDescendingTitleOrder() async { try { final posts = await Amplify.DataStore.query( Post.classType, sortBy: [ Post.RATING.ascending(), Post.TITLE.descending(), ], ); safePrint('Posts: $posts'); } on DataStoreException catch (e) { safePrint('Something went wrong querying posts: ${e.message}'); }}
Pagination
Query results can also be paginated by passing in a page
number (starting at 0) and an optional limit
(defaults to 100). This will return a list of the first 100 items:
import 'package:amplify_flutter/amplify_flutter.dart';
import 'models/ModelProvider.dart';
Future<void> queryPostsWithPagination(int page) async { try { final posts = await Amplify.DataStore.query( Post.classType, pagination: QueryPagination(page: page, limit: 25), ); safePrint('Posts: $posts'); } on DataStoreException catch (e) { safePrint('Something went wrong querying posts: ${e.message}'); }}