【问题标题】:How can I parse json data from websocket server in flutter?如何在flutter中解析来自websocket服务器的json数据?
【发布时间】:2021-05-10 08:28:41
【问题描述】:

WebSocket 服务器应该在它启动时立即拍摄 json 数据,我想创建一个 StreamBuilder,它在拍摄我时更新数据 FutureBuilder 已收到异步并等待 http.get,我该如何制作为我的直播生成器直播?

当我从 http 服务器接收信息时,这里是 futurebuilder!(所有信息,不是实时的) 我想通过streambuilder从websocket服务器实时接收这样的信息!

class BallInformationWidget extends StatefulWidget {
  @override
  BallInformationWidgetState createState() => BallInformationWidgetState();
}

class BallInformationWidgetState extends State<BallInformationWidget> {
  @override
  Widget build(BuildContext context) {
    return FutureBuilder<List<BallInformation>>(
      future: getHttpBallInfo(urlPrefix),
      builder: (context, snapshot) {
        print('http data : ${snapshot.data}');
        print('http length : ${snapshot.data.length}\n');
        print('http type : ${snapshot.data[0].id.runtimeType}\n');
        BallInformation ballInfo = snapshot.data[0]; // 공하나 객체 선언 후에 for 문?
        return Padding(
          padding: const EdgeInsets.symmetric(vertical: 5.0),
          child: Text(snapshot.hasData ? '${ballInfo.id}' : 'Loading...'),
        );
      },
    );
  }
}

class BallInformation {
  int id;
  double speed;
  String result;
  Map trajectoryParameter;

  BallInformation(this.id, this.speed, this.result, this.trajectoryParameter);

  BallInformation.fromJson(Map<String, dynamic> data) {
    this.id = data['id'];
    this.speed = data['speed'];
    this.result = data['result'];
    this.trajectoryParameter = data['trajectory_parameter'];
  }
}

Future<List<BallInformation>> getHttpBallInfo(String url) async {
  http.Response response = await http.get(url);
  String responseBody = response.body;
  var dataS = json.decode(responseBody);
  List<BallInformation> ballInformation = [];
  // If I receive json(only one information
  ballInformation.add(BallInformation.fromJson(dataS));
  // If I receive json(List, more than 1 information)
  // for (var data in dataS){
  //   ballInformation.add(BallInformation.fromJson(data));
  // }
  return ballInformation;
}

【问题讨论】:

标签: json flutter websocket real-time stream-builder


【解决方案1】:

这个的标准方法是json.decode(snapshot.data)。这将在请求中返回您的 json 数据的映射。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-24
    • 1970-01-01
    • 2016-04-02
    • 2014-05-25
    相关资源
    最近更新 更多