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

Page updated Apr 29, 2024

Subscribe to real-time events

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.

Subscribe to mutations for creating real-time clients.

Setup subscription with callbacks

When creating subscriptions, a Stream object will be returned to you. This Stream will continue producing events until either the subscription encounters an error or you cancel the subscription. In the case of need for limiting the amount of data that is omitted, you can take advantage of the Stream's helper functions such as take. The cancellation occurs when the defined amount of event has occurred:

1Stream<GraphQLResponse<Todo>> subscribe() {
2 final subscriptionRequest = ModelSubscriptions.onCreate(Todo.classType);
3 final Stream<GraphQLResponse<Todo>> operation = Amplify.API
4 .subscribe(
5 subscriptionRequest,
6 onEstablished: () => print('Subscription established'),
7 )
8 // Listens to only 5 elements
9 .take(5)
10 .handleError(
11 (error) {
12 print('Error in subscription stream: $error');
13 },
14 );
15 return operation;
16}

Alternatively, you can call Stream.listen to create a StreamSubscription object which can be programmatically canceled.

1// Be sure to import this
2import 'dart:async';
3
4...
5
6StreamSubscription<GraphQLResponse<Todo>>? subscription;
7
8void subscribe() {
9 final subscriptionRequest = ModelSubscriptions.onCreate(Todo.classType);
10 final Stream<GraphQLResponse<Todo>> operation = Amplify.API.subscribe(
11 subscriptionRequest,
12 onEstablished: () => print('Subscription established'),
13 );
14 subscription = operation.listen(
15 (event) {
16 print('Subscription event data received: ${event.data}');
17 },
18 onError: (Object e) => print('Error in subscription stream: $e'),
19 );
20}
21
22void unsubscribe() {
23 subscription?.cancel();
24}

Note that in addition to an onCreate subscription, you can also call .onUpdate() or .onDelete().

1final onUpdateSubscriptionRequest = ModelSubscriptions.onUpdate(Todo.classType);
2// or
3final onDeleteSubscriptionRequest = ModelSubscriptions.onDelete(Todo.classType);