首页 > 解决方案 > 如何使用 Flutter dart 运行计时器?

问题描述

我想在我的应用程序中实现一个计时器。从0开始计数,依此类推。如果用户杀死应用程序,然后再次打开,我想继续计算我杀死的地方。谁可以帮我这个事。谢谢。

例如:

标签: flutterdart

解决方案


这是使用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),
            ),
          ),
        ),
      ),
    );
  }
}

推荐阅读