dart - 如何使用 Flutter 消费 GraphQL 订阅?
问题描述
我正在使用 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"
}
}
}
如果您像我一样只想直接使用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();
},
);
}
}
当我使用 StreamBuilder 构建小部件时,它将负责关闭流。如果您不是这种情况,stream.listen()
方法将返回一个StreamSubscription<FetchResult>
对象,您可以调用该cancel()
方法,该方法可以在dispose()
有状态小部件的方法或独立客户端的任何此类方法中完成Dart
。
推荐阅读
- python - Python:如何将列表中的变量分配给字符串,然后将该字符串添加到不同的列表中?
- swift - 在 StoreKit 中使用多个产品标识符时 SwiftUI 应用程序冻结
- java - 如何在退出 JFrame 时停止 AudioSystem?
- c - BinaryTree 无法删除根节点
- html - 我错过了一些关于响应式设计的东西
- asp.net - 如何让本地 IIS 使用不同的 Azure Active Directory 访问资源
- java - 如何证明两个孩子是兄弟姐妹?
- sass - 如何将 2 个 SCSS 规则之间的共同点保留为单个规则并创建一个具有差异的新规则
- python - 在字典列表中将一些 python 字典键重新分配为值,将其他值重新分配为键
- java - 如何在 Windows 操作系统上删除或禁用 Java 中的“制表符选择器”?