如何在Flutter中使用graphql订阅?

时间:2019-03-24 07:44:28

标签: flutter graphql-subscriptions

我正在使用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');
                }
              }
            ),
          ],
        ),
      ),
    );
  }

}

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

0 个答案:

没有答案