【问题标题】:Flutter json_rpc_2 implementationFlutter json_rpc_2 实现
【发布时间】:2018-10-05 16:58:41
【问题描述】:

有人用json_rpc_2包成功实现了WebSocket吗?https://pub.dartlang.org/packages/json_rpc_2

我尝试呈现实时数据,例如一个股票代码,来自这个 API:https://api.hitbtc.com/

【问题讨论】:

  • 网络套接字?当您同时控制服务器和客户端时,Websockets 非常适合双向通信。但这里不是这样。相反,为什么不对这个数据源使用 HTTP 协议呢? link1link2。更新...哇,那个api提供了套接字连接。你真的需要那个吗?

标签: dart flutter json-rpc


【解决方案1】:

实际上,我设法解决了这个问题。代码如下:

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:json_rpc_2/json_rpc_2.dart' as json_rpc;
import 'package:web_socket_channel/io.dart';

class SymbolDetails extends StatelessWidget {
  final String symbolId;

  SymbolDetails({this.symbolId});

  @override
  Widget build(BuildContext context) {
    var _api = IOWebSocketChannel.connect('wss://api.hitbtc.com/api/2/ws');
    var client = json_rpc.Client(_api.cast());
    client.sendNotification(
      'subscribeTicker',
      {'symbol': '$symbolId'},
    );
    return Scaffold(
      appBar: AppBar(
        title: Text('$symbolId details'),
      ),
      body: StreamBuilder(
        stream: _api.stream,
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          if (snapshot.connectionState == ConnectionState.none) {
            return Center(
              child: Text('Please check your internet connection'),
            );
          } else if (!snapshot.hasData) {
            return Center(child: CircularProgressIndicator());
          }
          String _snapshotData = snapshot.data;
          Map _response = json.decode(_snapshotData);
          return ListView(
            children: [
              ListTile(
                title: Text('Ask price:'),
                trailing: Text(
                  '${_response['params']['ask']}',
                  style: TextStyle(fontWeight: FontWeight.bold),
                ),
              ),
              ListTile(
                title: Text('Bid price:'),
                trailing: Text(
                  '${_response['params']['bid']}',
                  style: TextStyle(fontWeight: FontWeight.bold),
                ),
              ),
            ],
          );
        },
      ),
    );
  }
}

【讨论】:

    猜你喜欢
    • 2020-09-13
    • 2019-02-25
    • 2019-01-21
    • 2017-10-26
    • 2021-10-26
    • 1970-01-01
    • 1970-01-01
    • 2020-11-11
    • 2019-02-07
    相关资源
    最近更新 更多