簡體   English   中英

Flutter - 手動觸發 StreamSubscription onData

[英]Flutter - Triggering StreamSubscription onData Manually

我在 flutter 中使用計步器插件,我注意到的一件事是,當我在一段時間后打開應用程序時,顯示的步數不會更新,直到我在打開應用程序時執行步驟以觸發 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);
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM