我有一堂课,其中发生了与Strophe的连接,并且我不断收到传入的消息。我希望每次收到新消息时,将其发送到另一个生成聊天界面的类,以在屏幕上显示该消息。但是我不知道该怎么做。
这是接收消息的功能。我想要的是每次收到新消息时都将message
发送给另一个班级。
onMessage(xml.XmlElement msg) {
var to = msg.getAttribute('to');
var from = msg.getAttribute('from');
var type = msg.getAttribute('type');
List<xml.XmlElement> body = msg.findElements('body').toList();
var now = new DateTime.now();
NewMessage message = NewMessage();
message.from = from;
message.fecha = now.toString();
message.body = body.map((node) => node.text).elementAt(0);
message.read = false;
// we must return true to keep the handler alive.
// returning false would remove it after it finishes.
return true;
}
答案 0 :(得分:1)
在这种情况下,您可以使用Stream
简单示例:
import 'dart:async';
void main() {
//
// Initialize a "Single-Subscription" Stream controller
//
final StreamController ctrl = StreamController();
//
// Initialize a single listener which simply prints the data
// as soon as it receives it
//
final StreamSubscription subscription = ctrl.stream.listen((data) => print('$data'));
//
// We here add the data that will flow inside the stream
//
ctrl.sink.add('my name');
ctrl.sink.add(1234);
ctrl.sink.add({'a': 'element A', 'b': 'element B'});
ctrl.sink.add(123.45);
//
// We release the StreamController
//
ctrl.close();
}
BLoC模式最适合您。 BLoC Pattern