如果流没有返回连接值,我需要从函数返回结果。
所以我有外部函数和内部函数。如何从外部内部返回结果?
Future<bool> send() async {
var subscription = Connectivity().onConnectivityChanged.listen((ConnectivityResult result) {
if(result == ConnectivityResult.none)
throw("No connectivity");
// Need to stop `send` function here and return some result
});
await doSomeWork();
return true;
}
最佳答案
send
返回的 Future
只能完成一次,而 Stream
可能会发出多个事件 - 你无法完成它使用 true
然后再次使用 false
完成,因为一些新事件来自流。
您可以决定 send
的返回值取决于流中的第一个 事件:
Future<bool> send() async {
var result = await Connectivity().onConnectivityChange.first;
if (result == ConnectivityResult.none) {
// handle no connection
return false;
}
await doSomeWork(); // only happens if the first result was not `none`
return true;
}
或者您需要决定 none
连接结果在之后 doSomeWork()
是什么意思已经调用并且从 send
返回的 Future
已经完成。
关于flutter - 内部流监听 DART 的返回结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56532990/