【问题标题】:Flutter - Triggering StreamSubscription onData ManuallyFlutter - 手动触发 StreamSubscription onData
【发布时间】:2019-10-07 18:54:09
【问题描述】:

我在flutter中使用pedometer插件,我注意到的一件事是,当我在一段时间后打开应用程序时,显示的步数不会更新,直到我在打开应用程序时执行步骤以触发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));
}

}

【问题讨论】:

  • 不清楚,_onData 是否被调用?如果是,那是什么问题?
  • 好的,我会重新写问题。问题是我想在应用程序恢复时自己调用 _onData,没有真正的步骤
  • 它是采用一个int 参数的常规方法......那么它有什么问题?
  • 问题是我想访问当前 stepCountValue 以便在应用程序恢复时更新当前步骤;否则,用户需要执行一些步骤才能调用 onData。他会看到他上次打开应用程序的步数,除非他这样做,否则不会显示在后台收集的步数。
  • pedometer.stepCountStream 流总是 0、1、2、3 等?

标签: dart flutter subscription pedometer


【解决方案1】:
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);
  }
}

【讨论】:

  • 虽然此代码可能会为问题提供解决方案,但最好添加有关其工作原理/方式的上下文。这可以帮助未来的用户学习并将这些知识应用到他们自己的代码中。在解释代码时,您也可能会以赞成票的形式从用户那里获得积极的反馈。
猜你喜欢
  • 1970-01-01
  • 2021-08-09
  • 1970-01-01
  • 2023-04-08
  • 2019-07-20
  • 2011-12-27
  • 2017-04-01
  • 2019-04-03
  • 1970-01-01
相关资源
最近更新 更多