2

我正在使用flutter_graphql插件,它对于查询和突变工作正常,但我面临订阅问题。

以下是我尝试过的代码,但它只是打印加载甚至没有命中服务器。

import 'package:flutter/material.dart';
import 'package:flutter_graphql/flutter_graphql.dart';

void main() async {
  socketClient = await SocketClient.connect('ws://address',
    headers: {
      'authorization': "accessTokenHere"
    }
  );

  runApp(MyApp());
}

class MyApp extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    final title = 'WebSocket Demo';
    return MaterialApp( 
      title: title,
      home: MyHomePage(
        title: title,
      ),
    );
  }
}

class MyHomePage extends StatefulWidget {
  final String title;

  MyHomePage({Key key, @required this.title})
      : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  TextEditingController _controller = TextEditingController();

  static String operationName = "notification";
  String query = """subscription $operationName{
    notification{
      messageCount
    }
  }""".replaceAll('\n', ' ');

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Padding(
        padding: const EdgeInsets.all(20.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Form(
              child: TextFormField(
                controller: _controller,
                decoration: InputDecoration(labelText: 'Send a message'),
              ),
            ),
            Subscription(
              operationName,
              query,
              variables: {},
              builder: ({
                bool loading,
                dynamic payload,
                dynamic error,
              }) {
                print(loading);
                print(payload);
                print(error);
                if (payload != null) {
                  return Text(payload['requestSubscription']['requestData']);
                } else {
                  return Text('Data not found');
                }
              }
            ),
          ],
        ),
      ),
    );
  }

}

我想使用订阅从服务器接收消息计数以向用户提供通知。

4

1 回答 1

0

flutter_graphql插件已停产,您可能需要考虑迁移到graphql_flutter。要订阅 Subscription,您可以将其Subscription.options()作为SubscriptionOptions添加到属性中

Subscription(
  options: SubscriptionOptions(
    document: subscriptionDocument, // subscribe to the document
  ),
  builder: (result) {
    if (result.hasException) {
      // Catch errors
      return Text(result.exception.toString());
    }

    if (result.isLoading) {
      // Display progress
      return Center(
        child: const CircularProgressIndicator(),
      );
    }
 
    // else, display data
    return Widget(...);
  }
)
于 2022-02-15T23:07:04.563 回答