Using GraphQL Subscriptions in Flutter
Sep 5, 2025



Summary
Summary
Summary
Summary
This tutorial covers integrating GraphQL subscriptions into Flutter apps with the `graphql_flutter` package. Learn how to set up HTTP and WebSocket links, define subscription documents, use the `Subscription` widget for UI updates, handle reconnection and errors, and apply best practices like data normalization and throttling for smooth, real-time mobile development.
This tutorial covers integrating GraphQL subscriptions into Flutter apps with the `graphql_flutter` package. Learn how to set up HTTP and WebSocket links, define subscription documents, use the `Subscription` widget for UI updates, handle reconnection and errors, and apply best practices like data normalization and throttling for smooth, real-time mobile development.
This tutorial covers integrating GraphQL subscriptions into Flutter apps with the `graphql_flutter` package. Learn how to set up HTTP and WebSocket links, define subscription documents, use the `Subscription` widget for UI updates, handle reconnection and errors, and apply best practices like data normalization and throttling for smooth, real-time mobile development.
This tutorial covers integrating GraphQL subscriptions into Flutter apps with the `graphql_flutter` package. Learn how to set up HTTP and WebSocket links, define subscription documents, use the `Subscription` widget for UI updates, handle reconnection and errors, and apply best practices like data normalization and throttling for smooth, real-time mobile development.
Key insights:
Key insights:
Key insights:
Key insights:
Setting Up the GraphQL Client: Initialize
HttpLink
andWebSocketLink
then combine them withLink.split
for queries and subscriptions.Defining and Managing Subscriptions: Write GraphQL subscription documents and use
client.subscribe
to receive a stream of live updates.Integrating Subscriptions into Widgets: Use the
Subscription
widget’s builder to handle loading, error, and data states seamlessly in the UI.Handling Errors and Reconnection: Enable
autoReconnect
, catchresult.exception
, and offer user-triggered retries to ensure reliability.Best Practices for Real-Time Data: Normalize cache, throttle updates, clean up streams, reuse fragments, and secure WebSocket connections.
Introduction
In modern mobile development, real-time data is crucial for chat apps, live dashboards, and collaborative tools. GraphQL subscriptions allow Flutter applications to receive continuous updates over WebSockets. This tutorial walks through integrating GraphQL subscriptions into Flutter using the graphql_flutter
package, from client setup to best practices for handling reconnection and errors.
Setting Up the GraphQL Client
Begin by adding dependencies to your pubspec.yaml
:
dependencies:
flutter:
sdk: flutter
graphql_flutter
Initialize a GraphQLClient
with both HTTP and WebSocket links. The HTTP link handles queries and mutations, while the WebSocket link manages subscriptions.
final httpLink = HttpLink('https://api.example.com/graphql');
final webSocketLink = WebSocketLink(
'wss://api.example.com/subscriptions',
config: const SocketClientConfig(
autoReconnect: true,
inactivityTimeout: Duration(seconds: 30),
),
);
final link = Link.split(
(request) => request.isSubscription,
webSocketLink,
httpLink,
);
final client = GraphQLClient(
cache: GraphQLCache(store: InMemoryStore()),
link: link,
);
Wrap your app with GraphQLProvider
to make the client available throughout your widget tree.
Defining and Managing Subscriptions
Define a GraphQL subscription document. For example, listening to new chat messages:
subscription OnMessageAdded($roomId: ID!) {
messageAdded(roomId: $roomId) {
id
content
sender {
id
name
}
timestamp
}
}
Use Dart to parse variables and execute the subscription stream:
const messageSubscription = r'''
subscription OnMessageAdded($roomId: ID!) {
messageAdded(roomId: $roomId) {
id
content
sender { id name }
timestamp
}
}
''';
Stream<FetchResult> subscribeToMessages(GraphQLClient client, String roomId) {
return client.subscribe(
SubscriptionOptions(
document: gql(messageSubscription),
variables: {'roomId': roomId},
),
);
}
This stream emits data whenever a new message arrives. You can transform it into model objects and manage state accordingly.
Integrating Subscriptions into Widgets
The Subscription
widget from graphql_flutter
simplifies UI integration by providing a builder callback with result
updates.
Subscription(
options: SubscriptionOptions(
document: gql(messageSubscription),
variables: {'roomId': roomId},
),
builder: (result) {
if (result.isLoading) return CircularProgressIndicator();
if (result.hasException) return Text(result.exception.toString());
final data = result.data!['messageAdded'];
return ListTile(
title: Text(data['sender']['name']),
subtitle: Text(data['content']),
trailing: Text(data['timestamp']),
);
},
)
Within builder
, handle loading, error and data states. Integrate this widget inside your chat screen or list view builder.
Handling Errors and Reconnection
Network glitches or server interruptions can disrupt WebSocket connections. Configure SocketClientConfig.autoReconnect
to true, as shown above, and provide inactivityTimeout
to detect stale connections.
In your UI, watch for subscription errors and display retry options:
Inspect
result.exception
for GraphQL or network errors.Show a SnackBar or AlertDialog prompting the user to retry.
Re-create the subscription stream if needed by calling
client.subscribe
again.
Example error handler within builder
:
if (result.hasException) {
return Column(
children: [
Text('Connection lost'),
ElevatedButton(
onPressed: () => setState(() {}),
child: Text('Retry'),
),
],
);
}
Best Practices for Real-Time Data
Normalize Data in Cache: Use
GraphQLCache
withInMemoryStore
to prevent duplicate entries.Throttle UI Updates: For high-frequency events, batch state updates to avoid UI jank.
Clean Up Subscriptions: Dispose of subscription streams on widget unmount to prevent memory leaks.
Use Fragments: Define reusable fragments for consistent data shapes across queries and subscriptions.
Secure WebSocket Connections: Always authenticate WebSocket links with valid tokens and refresh them before expiration.
Vibe Studio

Vibe Studio, powered by Steve’s advanced AI agents, is a revolutionary no-code, conversational platform that empowers users to quickly and efficiently create full-stack Flutter applications integrated seamlessly with Firebase backend services. Ideal for solo founders, startups, and agile engineering teams, Vibe Studio allows users to visually manage and deploy Flutter apps, greatly accelerating the development process. The intuitive conversational interface simplifies complex development tasks, making app creation accessible even for non-coders.
Conclusion
GraphQL subscriptions offer a powerful way to implement real-time features in Flutter mobile development. By configuring both HTTP and WebSocket links, defining subscription documents, integrating Subscription
widgets, and applying best practices for caching and error handling, you can build responsive, live-updating apps. With these patterns, your Flutter app will deliver seamless, real-time user experiences.
Introduction
In modern mobile development, real-time data is crucial for chat apps, live dashboards, and collaborative tools. GraphQL subscriptions allow Flutter applications to receive continuous updates over WebSockets. This tutorial walks through integrating GraphQL subscriptions into Flutter using the graphql_flutter
package, from client setup to best practices for handling reconnection and errors.
Setting Up the GraphQL Client
Begin by adding dependencies to your pubspec.yaml
:
dependencies:
flutter:
sdk: flutter
graphql_flutter
Initialize a GraphQLClient
with both HTTP and WebSocket links. The HTTP link handles queries and mutations, while the WebSocket link manages subscriptions.
final httpLink = HttpLink('https://api.example.com/graphql');
final webSocketLink = WebSocketLink(
'wss://api.example.com/subscriptions',
config: const SocketClientConfig(
autoReconnect: true,
inactivityTimeout: Duration(seconds: 30),
),
);
final link = Link.split(
(request) => request.isSubscription,
webSocketLink,
httpLink,
);
final client = GraphQLClient(
cache: GraphQLCache(store: InMemoryStore()),
link: link,
);
Wrap your app with GraphQLProvider
to make the client available throughout your widget tree.
Defining and Managing Subscriptions
Define a GraphQL subscription document. For example, listening to new chat messages:
subscription OnMessageAdded($roomId: ID!) {
messageAdded(roomId: $roomId) {
id
content
sender {
id
name
}
timestamp
}
}
Use Dart to parse variables and execute the subscription stream:
const messageSubscription = r'''
subscription OnMessageAdded($roomId: ID!) {
messageAdded(roomId: $roomId) {
id
content
sender { id name }
timestamp
}
}
''';
Stream<FetchResult> subscribeToMessages(GraphQLClient client, String roomId) {
return client.subscribe(
SubscriptionOptions(
document: gql(messageSubscription),
variables: {'roomId': roomId},
),
);
}
This stream emits data whenever a new message arrives. You can transform it into model objects and manage state accordingly.
Integrating Subscriptions into Widgets
The Subscription
widget from graphql_flutter
simplifies UI integration by providing a builder callback with result
updates.
Subscription(
options: SubscriptionOptions(
document: gql(messageSubscription),
variables: {'roomId': roomId},
),
builder: (result) {
if (result.isLoading) return CircularProgressIndicator();
if (result.hasException) return Text(result.exception.toString());
final data = result.data!['messageAdded'];
return ListTile(
title: Text(data['sender']['name']),
subtitle: Text(data['content']),
trailing: Text(data['timestamp']),
);
},
)
Within builder
, handle loading, error and data states. Integrate this widget inside your chat screen or list view builder.
Handling Errors and Reconnection
Network glitches or server interruptions can disrupt WebSocket connections. Configure SocketClientConfig.autoReconnect
to true, as shown above, and provide inactivityTimeout
to detect stale connections.
In your UI, watch for subscription errors and display retry options:
Inspect
result.exception
for GraphQL or network errors.Show a SnackBar or AlertDialog prompting the user to retry.
Re-create the subscription stream if needed by calling
client.subscribe
again.
Example error handler within builder
:
if (result.hasException) {
return Column(
children: [
Text('Connection lost'),
ElevatedButton(
onPressed: () => setState(() {}),
child: Text('Retry'),
),
],
);
}
Best Practices for Real-Time Data
Normalize Data in Cache: Use
GraphQLCache
withInMemoryStore
to prevent duplicate entries.Throttle UI Updates: For high-frequency events, batch state updates to avoid UI jank.
Clean Up Subscriptions: Dispose of subscription streams on widget unmount to prevent memory leaks.
Use Fragments: Define reusable fragments for consistent data shapes across queries and subscriptions.
Secure WebSocket Connections: Always authenticate WebSocket links with valid tokens and refresh them before expiration.
Vibe Studio

Vibe Studio, powered by Steve’s advanced AI agents, is a revolutionary no-code, conversational platform that empowers users to quickly and efficiently create full-stack Flutter applications integrated seamlessly with Firebase backend services. Ideal for solo founders, startups, and agile engineering teams, Vibe Studio allows users to visually manage and deploy Flutter apps, greatly accelerating the development process. The intuitive conversational interface simplifies complex development tasks, making app creation accessible even for non-coders.
Conclusion
GraphQL subscriptions offer a powerful way to implement real-time features in Flutter mobile development. By configuring both HTTP and WebSocket links, defining subscription documents, integrating Subscription
widgets, and applying best practices for caching and error handling, you can build responsive, live-updating apps. With these patterns, your Flutter app will deliver seamless, real-time user experiences.
Build Flutter Apps Faster with Vibe Studio
Build Flutter Apps Faster with Vibe Studio
Build Flutter Apps Faster with Vibe Studio
Build Flutter Apps Faster with Vibe Studio
Vibe Studio is your AI-powered Flutter development companion. Skip boilerplate, build in real-time, and deploy without hassle. Start creating apps at lightning speed with zero setup.
Vibe Studio is your AI-powered Flutter development companion. Skip boilerplate, build in real-time, and deploy without hassle. Start creating apps at lightning speed with zero setup.
Vibe Studio is your AI-powered Flutter development companion. Skip boilerplate, build in real-time, and deploy without hassle. Start creating apps at lightning speed with zero setup.
Vibe Studio is your AI-powered Flutter development companion. Skip boilerplate, build in real-time, and deploy without hassle. Start creating apps at lightning speed with zero setup.











