gpt4 book ai didi

flutter - 如何将Future 转换为Stream

转载 作者:行者123 更新时间:2023-12-03 02:55:09 29 4
gpt4 key购买 nike

在我的Flutter应用中,我有一个返回Future的函数,但我想将结果作为Stream。这是函数:

  Future<bool> isGpsOn() async {
if (await Geolocator().isLocationServiceEnabled()) {
return true;
} else {
return false;
}
}

怎么做?

最佳答案

阅读manual并检查我的答案:

Stream<bool> gpsStatusStream() async* {
bool enabled;
while (true) {
try {
bool isEnabled = await Geolocator().isLocationServiceEnabled();
if (enabled != isEnabled) {
enabled = isEnabled;
yield enabled;
}
}
catch (error) {}
await Future.delayed(Duration(seconds: 5));
}
}

gpsStatusStream().listen((enabled) {
print(enabled ? 'enabled' : 'disabled');
});

或创建转换器:

Stream futureToStream(fn, defaultValue, Duration duration) async* {
var result;
while (true) {
try {
result = await fn();
}
catch (error) {
result = defaultValue;
}
finally {
yield result;
}
await Future.delayed(duration);
}
}

Future<bool> isGpsOn() async {
return await Geolocator().isLocationServiceEnabled();
}

final gpsStatusStream = futureToStream(isGpsOn, false, Duration(seconds: 5));
gpsStatusStream.listen((enabled) {
print(enabled ? 'enabled' : 'disabled');
});

关于flutter - 如何将Future <bool>转换为Stream <bool>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61972889/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com