颤振如何聆听websocket的响应? [英] Flutter how to listen to websocket response?

查看:31
本文介绍了颤振如何聆听websocket的响应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

众所周知,flutter有一个使用websocket的示例,但是它只是以流的形式接收websocket的响应,就像这样:

As we all know, flutter has an example of using websocket, but it just receive websocket response as stream, and just something like this:

new StreamBuilder(
  stream: widget.channel.stream,
  builder: (context, snapshot) {
    return new Text(snapshot.hasData ? '${snapshot.data}' : '');
  },
);

我想要的是一个异步函数,该函数接收每个websocket响应并将结果附加到列表中,以便可以更新listview.

What I am want is an async function which receives every websocket response and append the result to a list, so that the listview can be updated.

无论如何如何以文本或json形式获取websocket响应?

How to get the websocket response as text or json anyway?

更新:我知道现在有一些类似stream.listen的方法:

Update: I know there are some method like stream.listen now:

widget.channel.stream.listen((data) {
  print("!!!!new msg: $data");
  var dataJson = json.decode(data);
  print(dataJson["content"]);
  // do something after received data
  setState(() {
    _allAnimateMessages.insert(0, newMsg);
  });
  newMsg.animationController.forward();
});

这可以在页面中工作,但是当再次进入该页面时,出现错误,提示 Bad状态:流已经被监听..如何使流在每次开始时都能被监听,然后广播到许多页面?

This can work in a page, but when enter that page again, there was an error says Bad state: Stream has already been listened to.. How to make the stream can be listened at every begaining, and then boradcast to many pages?

推荐答案

请确保在离开当前窗口小部件时关闭WebSocket连接.在小部件的 State 类中,您应该具有一个如下所示的 dispose()方法:

Make sure you are closing your WebSocket connection when you leave the current widget. Inside your widget's State class you should have a dispose() method that looks like this:

@override
void dispose() {
  widget.channel.sink.close();
  super.dispose();
}

这篇关于颤振如何聆听websocket的响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆