dart - Flutter - 手动触发 StreamSubscription onData
问题描述
我在颤振中使用计步器插件,我注意到的一件事是,当我在一段时间后打开应用程序时,显示的步数不会更新,直到我在打开应用程序时执行步骤以触发 StreamSubscription 的 onData 方法. 这不是setState
问题,因为它每秒更新一次。
以下是我到目前为止所做的与此相关的部分工作:
class _MyScreenState extends State<MyScreen>
with AutomaticKeepAliveClientMixin<Page1>, WidgetsBindingObserver {
StreamSubscription _subscription;
final Store<AppState> store;
_MyScreenState(this.store, this.pedometer);
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
setUpPedometer();
}
void setUpPedometer() {
_subscription = pedometer.stepCountStream
.listen(_onData, onError: _onError, cancelOnError: true);
}
@override
Future<Null> didChangeAppLifecycleState(AppLifecycleState state) async {
if (state == AppLifecycleState.resumed) {
await resumeCallBack();
}
}
resumeCallBack() {
// here, I am looking for a way to trigger onData method
}
void _onData(int stepCountValue) async {
print("stepCountValue : ${stepCountValue}");
store.dispatch(UpdateStepsAction(
steps: stepCountValue));
}
}
解决方案
import 'dart:async';
import 'package:pedometer/pedometer.dart';
class PedometerController{
static Future<int> getStepsFromPedometer() async{
StreamController<int> streamHelper = new StreamController();
var pedometer = Pedometer();
pedometer.pedometerStream.listen((v){
streamHelper.sink.add(v);
streamHelper.close();
});
return await whenTrue(streamHelper.stream);
}
static Future<int> whenTrue(Stream<int> source) {
return source.firstWhere((int item) => item > -1);
}
}
推荐阅读
- python - Geopandas多边形到线
- sql-server - SQL 结合了多个计划的可用性和限制信息
- vue.js - vue.js 和事件中的数据绑定问题
- c# - 如何自动创建子类的实例列表,以便能够在应用程序启动时对这些“脚本”调用“执行”方法?
- firebase - 为什么可以使用 Firebase AUth Api 向外部提供商发送密码重置电子邮件?
- tfs - 通过命令行配置团队资源管理器
- stdout - 如何在 Pharo/Squeak 中从标准输入读取并写入 WindowsProcess 的标准输出?
- mysql - 计算 MySQL 5.6 中重叠日期范围的最大数量
- python - 使用日期时间对象作为散点图?
- java - java数组随机扫描器类