[英]How can I parse json data from websocket server in flutter?
The WebSocket server is supposed to shoot json data as soon as it goes up, and I want to create a StreamBuilder that updates the data as it shoots me FutureBuilder has received async and wait http.get, and how do I make a Stream for my stream 建造者?
当我从 http 服务器接收信息时,这里是 futurebuilder,(对于所有信息,不是实时的)我想通过流构建器从 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.decode(snapshot.data)
。 这将在请求中返回 json 数据的 map。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.