简体   繁体   English

如何使用 Flutter dart 运行计时器?

[英]How to run a timer using Flutter dart?

I want to implement a timer in my application.我想在我的应用程序中实现一个计时器。 Which counts from 0 and so on.从 0 开始计数,依此类推。 If user kills the app, and open again i want to continue with the count where i killed.如果用户杀死了应用程序,然后再次打开,我想继续计算我杀死的地方。 Can anyone help me on this.谁可以帮我这个事。 Thanks.谢谢。

For example:例如:

  • User Pressed start button, Now the count starts from 00:00 .用户按下开始按钮,现在计数从00:00开始。
  • User kills the app at 00:20 seconds用户在 00:20 秒杀死应用程序
  • Again when user opens the app, the timer should starts with 00:21再次当用户打开应用程序时,计时器应从00:21开始

Here's simple solution using shared_preferences and Timer .这是使用shared_preferencesTimer的简单解决方案。

const String _kTimeKey = 'time_s';

Future<void> main() async {
  final prefs = await SharedPreferences.getInstance();
  runApp(MyApp(dbTime: prefs.getInt(_kTimeKey)));
}

class MyApp extends StatefulWidget {
  final int dbTime;

  const MyApp({Key key, this.dbTime}) : super(key: key);

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  SharedPreferences _prefs;
  Timer _timer;
  int _currentSeconds;

  Future<void> _saveValue() async {
    await _prefs.setInt(_kTimeKey, _currentSeconds);
    _timer?.cancel();
    _timer = null;
  }

  @override
  void initState() {
    super.initState();  
    _currentSeconds = widget.dbTime ?? 0;
    _timer = Timer.periodic(Duration(seconds: 1), (_) => setState(() => _currentSeconds++));
    SharedPreferences.getInstance().then((prefs) async {
      _prefs = prefs;
    });
  }

  @override
  Future<void> dispose() async {
    await _saveValue();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(),
        body: WillPopScope(
          onWillPop: () async {
            await _saveValue();
            return true;
          },
          child: Center(
            child: Text(
              '$_currentSeconds',
              style: TextStyle(fontSize: 50),
            ),
          ),
        ),
      ),
    );
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM