'How to consume graphql subscriptions with flutter?
I am using the flutter_graphql plugin and it is working fine for queries and mutations but I am facing the problem with subscriptions.
Following is the code that I have tried out but it is just printing the loading not even hitting the server.
import 'package:flutter/material.dart';
import 'package:flutter_graphql/flutter_graphql.dart';
void main() async {
socketClient = await SocketClient.connect('ws://address',
headers: {
'authorization': "accessTokenHere"
}
);
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
final title = 'WebSocket Demo';
return MaterialApp(
title: title,
home: MyHomePage(
title: title,
),
);
}
}
class MyHomePage extends StatefulWidget {
final String title;
MyHomePage({Key key, @required this.title})
: super(key: key);
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
TextEditingController _controller = TextEditingController();
static String operationName = "notification";
String query = """subscription $operationName{
notification{
messageCount
}
}""".replaceAll('\n', ' ');
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Padding(
padding: const EdgeInsets.all(20.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Form(
child: TextFormField(
controller: _controller,
decoration: InputDecoration(labelText: 'Send a message'),
),
),
Subscription(
operationName,
query,
variables: {},
builder: ({
bool loading,
dynamic payload,
dynamic error,
}) {
print(loading);
print(payload);
print(error);
if (payload != null) {
return Text(payload['requestSubscription']['requestData']);
} else {
return Text('Data not found');
}
}
),
],
),
),
);
}
}
I want to receive the message count from the server using subscriptions to provide notification to the user.
Solution 1:[1]
flutter_graphql plugin has been discontinued, you may want to consider migrating to graphql_flutter. To subscribe to a Subscription, you can add it in Subscription.options()
property as SubscriptionOptions
Subscription(
options: SubscriptionOptions(
document: subscriptionDocument, // subscribe to the document
),
builder: (result) {
if (result.hasException) {
// Catch errors
return Text(result.exception.toString());
}
if (result.isLoading) {
// Display progress
return Center(
child: const CircularProgressIndicator(),
);
}
// else, display data
return Widget(...);
}
)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Omatt |