我有一个类(class),其中发生了与 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;
}
最佳答案
在这种情况下你可以使用 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
关于flutter - 将变量从一个类连续发送到另一个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52732562/