android - 如何在 Flutter 中实现持久秒表?

标签 android dart flutter dart-async

我正在 flutter 中实现一个计时器。这是应用程序的结构。

页面 A(包含一些列表,用户可以在其中单击并将其带到计时器页面)。 页面 B 格式,运行计时器。我能够正确运行计时器/秒表,但是当我按下页面 B 上的后退按钮时,我在处理错误后调用了 setstate()。我知道这是预期的行为。 如果我在处理时使用 timer.cancel(),我不会收到错误,但计时器将停止运行。计时器/秒表应该继续运行,即使我导航到页面 A 或说任何其他新页面(小部件)。 我知道这可能使用监听器和 WidgetBindingObserver 是可能的,但我对实现它还不清楚。希望我能在这个问题上得到一些帮助。

构建页面B类:

  Widget build(BuildContext context) {
return Scaffold(
    appBar: AppBar(
      leading: new IconButton(icon: new Icon(Icons.arrow_back), onPressed: ()async{
        Navigator.pop(context,widget._elapsedTime);
      }),
      title: Text("widget.title"),
    ),
    body: Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Text(
            '$_elapsedTime'),
          RaisedButton(
            child: Text('Start'),
            onPressed: () { 
              if(watch.isRunning){
                stopWatch();
              }
              else{
               startWatch();
              }
            },
          ),

        ],
      ),
    ));

StartWatch 函数:

startWatch() {
watch.start();
timer = new Timer.periodic(new Duration(milliseconds:1000), updateTime);}

每秒调用一次的更新时间函数:

updateTime(Timer timer) {
   if (watch.isRunning) {
   print(_elapsedTime);
   var time= formatedTime(watch.elapsedMilliseconds);
   print("time is"+time);
   setState(() {
        _elapsedTime = time;
   });
 }

最佳答案

这是一个最小的工作解决方案。要点:

  • 引入 TimerService 类来隔离计时器功能
  • TimerService 实现了 ChangeNotifier,您可以订阅它以接收更改。
  • InheritedWidget 用于为应用程序的所有小部件提供服务。这个继承的小部件包装了您的应用程序小部件。
  • AnimatedBuilder 用于接收来自 ChangeNotifier 的更改。订阅是自动处理的(无需手动 addListener/removeListener)。

import 'dart:async';

import 'package:flutter/material.dart';

void main() {
  final timerService = TimerService();
  runApp(
    TimerServiceProvider( // provide timer service to all widgets of your app
      service: timerService,
      child: MyApp(),
    ),
  );
}

class TimerService extends ChangeNotifier {
  Stopwatch _watch;
  Timer _timer;

  Duration get currentDuration => _currentDuration;
  Duration _currentDuration = Duration.zero;

  bool get isRunning => _timer != null;

  TimerService() {
    _watch = Stopwatch();
  }

  void _onTick(Timer timer) {
    _currentDuration = _watch.elapsed;

    // notify all listening widgets
    notifyListeners();
  }

  void start() {
    if (_timer != null) return;

    _timer = Timer.periodic(Duration(seconds: 1), _onTick);
    _watch.start();

    notifyListeners();
  }

  void stop() {
    _timer?.cancel();
    _timer = null;
    _watch.stop();
    _currentDuration = _watch.elapsed;

    notifyListeners();
  }

  void reset() {
    stop();
    _watch.reset();
    _currentDuration = Duration.zero;

    notifyListeners();
  }

  static TimerService of(BuildContext context) {
    var provider = context.inheritFromWidgetOfExactType(TimerServiceProvider) as TimerServiceProvider;
    return provider.service;
  }
}

class TimerServiceProvider extends InheritedWidget {
  const TimerServiceProvider({Key key, this.service, Widget child}) : super(key: key, child: child);

  final TimerService service;

  @override
  bool updateShouldNotify(TimerServiceProvider old) => service != old.service;
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Service Demo',
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    var timerService = TimerService.of(context);
    return Scaffold(
      appBar: AppBar(),
      body: Center(
        child: AnimatedBuilder(
          animation: timerService, // listen to ChangeNotifier
          builder: (context, child) {
            // this part is rebuilt whenever notifyListeners() is called
            return Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Text('Elapsed: ${timerService.currentDuration}'),
                RaisedButton(
                  onPressed: !timerService.isRunning ? timerService.start : timerService.stop,
                  child: Text(!timerService.isRunning ? 'Start' : 'Stop'),
                ),
                RaisedButton(
                  onPressed: timerService.reset,
                  child: Text('Reset'),
                )
              ],
            );
          },
        ),
      ),
    );
  }
}

关于android - 如何在 Flutter 中实现持久秒表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53228993/

相关文章:

android - 如何改变android中触摸按钮的颜色

android - Soundboard App 强制关闭,我不明白为什么

android - Adapter.getItem() 有什么用?

dart - 在 Flutter 中保存项目列表的状态

flutter - 使用定位的小部件在ListView.builder项小部件上添加小部件

java - SQLite相关用户信息检索

flutter - 在 iPhone 模拟器上测试 flutter 网站,但作为网站而不是应用程序

json - 如何获取带有对象列表的文档? -消防站

flutter - 在 Flutter web 中没有得到任何错误输出

flutter - list.forEach 在异步方法中没有正确等待