如何使用 Flutter 消费 GraphQL 订阅?

How to consume GraphQL Subscription with Flutter?

我正在使用 GraphQL 创建一个订阅,我需要使用 Flutter 使用该订阅,但我不知道该怎么做,我需要的东西类似于 UI 组件将与订阅相关联,并且会自动刷新。

如有任何反馈,我将不胜感激。

可以查看下一个库https://github.com/zino-app/graphql-flutter

只要找出这个库中的错误,只需通过 ctrl+单击订阅打开 subscription.dart 文件。在该文件中,很容易看出 socketClient 变量为空。所以只需在 initState() 函数中定义它,如文档中所示。重新启动您的应用程序。它就像一个魅力。所以,基本上,您只需要在 subscription.dart 文件中初始化该变量。

我的 GraphqlServer 运行一个名为 getLogs 的订阅,其中 return 以下列格式记录日志信息。

{
  "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() 方法将 return 一个 StreamSubscription<FetchResult> 对象,您可以调用 cancel() 方法,该方法可以在 dispose() 方法中完成用于独立 Dart 客户端的有状态小部件或任何此类方法。