我正在使用GraphQL创建订阅,并且需要使用Flutter使用该订阅,但是我不知道该怎么做,我需要做的事情是将UI组件绑定到订阅中它将自动刷新。
感谢您的反馈。
答案 0 :(得分:1)
答案 1 :(得分:0)
只需找出该库中的错误,只需按ctrl并单击Subscription即可打开subscription.dart文件。在该文件中,很容易看到socketClient变量为null。因此,只需按文档所示在initState()函数中对其进行定义。重新启动您的应用。它就像一种魅力。因此,基本上,您只需要在subscription.dart文件中初始化该变量即可。
答案 2 :(得分:0)
我的GraphqlServer运行名为getLogs
的订阅,该订阅以以下格式返回日志信息。
{
"data": {
"getLogs": {
"timeStamp": "18:09:24",
"logLevel": "DEBUG",
"file": "logger.py",
"function": "init",
"line": "1",
"message": "Hello from logger.py"
}
}
}
如果您和我一样只想直接使用GraphQL Client,那么以下示例可能会有所帮助。
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();
},
);
}
}
当我使用StreamBuilder构建小部件时,它将负责关闭流。如果您不是这种情况,则stream.listen()
方法将返回一个StreamSubscription<FetchResult>
对象,您可以调用该对象cancel()
,该对象可以在有状态窗口小部件的dispose()
方法中完成或用于独立Dart
客户端的任何此类方法。