首页 > 解决方案 > 如何使用 Flutter 消费 GraphQL 订阅?

问题描述

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

我将不胜感激任何反馈。

标签: dartfluttergraphqlsubscription

解决方案


我的 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


推荐阅读