如何在Flutter中实现永久秒表? [英] How to implement persistent stopwatch in Flutter?

查看:169
本文介绍了如何在Flutter中实现永久秒表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在实现一个定时器,这是应用程序的结构。

I am implementing a timer in flutter .Here is the structure of the app.

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

Page A (Contains some lists where user clicks and takes it to timer Page). Page B formats ,runs the timer .I am able to run the timer/stopwatch properly,but when i press the back button on Page B I get the setstate() called after dispose error.I understand that this is the expected behaviour. If i use timer.cancel() on dispose I wont be getting the error ,but the timer will stop running.The timer/stopwatch should continue to run even if i navigate to Page A or say any other new page(widget). I know that this may be possible using listeners and WidgetBindingObserver,But i have no clear knowledge of implementing it.Hope I'll get some help on this issue.

页面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 function:

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

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

Update Time function which gets called every second:

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


推荐答案

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

Here is a minimal working solution. Key points:


  • 介绍隔离计时器功能的 TimerService li>
  • TimerService 实现了 ChangeNotifier ,您可以订阅以接收更改。

  • InheritedWidget 用于为应用程序的所有小部件提供服务。此继承的窗口小部件将包装您的应用程序窗口小部件。

  • AnimatedBuilder 用于从 ChangeNotifier 。订阅是自动处理的(没有手动 addListener / removeListener )。

  • Introduction of a TimerService class that isolates the timer functionality
  • TimerService implements ChangeNotifier, which you can subscribe to to receive changes.
  • An InheritedWidget is used to provide the service to all widgets of your app. This inherited widget wraps your app widget.
  • AnimatedBuilder is used to receive changes from the ChangeNotifier. Subscriptions are handles automatically (no manual 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'),
                )
              ],
            );
          },
        ),
      ),
    );
  }
}

这篇关于如何在Flutter中实现永久秒表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆