flutter - 如何使用 Flutter dart 运行计时器?
问题描述
我想在我的应用程序中实现一个计时器。从0开始计数,依此类推。如果用户杀死应用程序,然后再次打开,我想继续计算我杀死的地方。谁可以帮我这个事。谢谢。
例如:
- 用户按下开始按钮,现在计数从00:00开始。
- 用户在 00:20 秒杀掉应用
- 同样,当用户打开应用程序时,计时器应从00:21开始
解决方案
这是使用shared_preferences和Timer的简单解决方案。
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),
),
),
),
),
);
}
}
推荐阅读
- javascript - 为什么document.cookie是一个空字符串请
- powershell - 将 jpg/pdf 文件分类到已按名称存在但仅使用前 6 位数字的文件夹中
- flutter - 当我没有用 Center Widget 包裹它时,为什么我的文本在中心?
- c# - 将 DbContext 和 DbSets 中的接口用于类似数据库
- snowflake-cloud-data-platform - 将上次更改时间戳添加到雪花表中
- angular - Angular Slickgrid 使用列标题重新加载数据
- bash - bash中目录的完整性
- asp.net-core - 如何允许其他人使用 LocalDb 运行 Web App
- javascript - 在javascript中保持后端功能打开
- scripting - 用于终止 Websphere 应用程序服务器上所有 JVM 的 Jython 脚本