Jos*_*aza 5 subscription dart graphql flutter
我正在使用 GraphQL 创建一个订阅,我需要使用 Flutter 使用该订阅,但我不知道如何做到这一点,我需要的东西就像一个与订阅相关联的 UI 组件,它会会自动刷新。
我将不胜感激任何反馈。
我的 GraphqlServer 运行一个名为的订阅getLogs,它以以下格式返回日志信息。
{
"data": {
"getLogs": {
"timeStamp": "18:09:24",
"logLevel": "DEBUG",
"file": "logger.py",
"function": "init",
"line": "1",
"message": "Hello from logger.py"
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果您像我一样只想直接使用GraphQL 客户端,那么以下示例可能会有所帮助。
import 'package:graphql/client.dart';
import 'package:graphql/internal.dart';
import 'package:flutter/material.dart';
import 'dart:async';
class LogPuller extends StatefulWidget {
static final WebSocketLink _webSocketLink = WebSocketLink(
url: 'ws://localhost:8000/graphql/',
config: SocketClientConfig(
autoReconnect: true,
),
);
static final Link _link = _webSocketLink;
@override
_LogPullerState createState() => _LogPullerState();
}
class _LogPullerState extends State<LogPuller> {
final GraphQLClient _client = GraphQLClient(
link: LogPuller._link,
cache: InMemoryCache(),
);
// the subscription query should be of the following format. Note how the 'GetMyLogs' is used as the operation name below.
final String subscribeQuery = '''
subscription GetMyLogs{
getLogs{
timeStamp
logLevel
file
function
line
message
}
}
''';
Operation operation;
Stream<FetchResult> _logStream;
@override
void initState() {
super.initState();
// note operation name is important. If not provided the stream subscription fails after first pull.
operation = Operation(document: subscribeQuery, operationName: 'GetMyLogs');
_logStream = _client.subscribe(operation);
}
@override
Widget build(BuildContext context) {
return StreamBuilder(
stream: _logStream,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(
child: Container(
child: CircularProgressIndicator(
strokeWidth: 1.0,
),
),
);
}
if (snapshot.hasData) {
return Center(
child: Text(
snapshot.data.data['getLogs']
['message'], // This will change according to you needs.
),
);
}
return Container();
},
);
}
}
Run Code Online (Sandbox Code Playgroud)
当我使用 StreamBuilder 来构建小部件时,它将负责关闭流。如果您不是这种情况,stream.listen()method 将返回一个StreamSubscription<FetchResult>对象,您可以调用该cancel()方法,该方法可以在dispose()有状态小部件的方法或独立Dart客户端的任何此类方法中完成。