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

11

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

页面A(包含一些列表,用户点击后会进入计时器页面)。 页面B格式化并运行计时器。我能够正确地运行计时器/秒表,但是当我在页面B上按返回按钮时,我会得到“setState() called after dispose”错误。我知道这是预期的行为。 如果我在dispose()方法中使用timer.cancel(),那么我就不会得到这个错误,但计时器将停止运行。即使我导航到页面A或者说任何其他新页面(widget),计时器/秒表也应该继续运行。 我知道可以使用listeners和WidgetBindingObserver来实现这个功能,但我并不清楚如何实现它。希望我能在这个问题上得到一些帮助。

页面B的Build类:

  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;
   });
 }
1个回答

31

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

  • 引入一个 TimerService 类来隔离计时器功能。
  • TimerService 实现了 ChangeNotifier 接口,你可以订阅它以接收更改通知。
  • 使用 InheritedWidget 来将该服务提供给你应用的所有小部件。这个继承的小部件包装你的应用小部件。
  • AnimatedBuilder 用于从 ChangeNotifier 接收更改通知,订阅处理自动进行(无需手动添加/删除监听器)。

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'),
                )
              ],
            );
          },
        ),
      ),
    );
  }
}

非常感谢您的回答,这个解决方案很有效。唯一的问题是如何修改它以实现多个定时器? - ganraj kelkar
在服务中,可以保留一个计时器列表(由StopwatchTimer组成)。向startstop方法添加一个int timerIndex参数。此时,只需要简单的代码,没有任何魔法。 - boformer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接