我一直在玩 Dart Timer Class,我让它以非常基本的形式工作,但是我试图向它添加暂停功能。我查看了他们的文档,但他们对 Timer 类的了解并不多......
有什么办法可以在点击时暂停和恢复计时器/倒计时?这是我迄今为止取得的成就:
import 'package:flutter/material.dart';
import 'dart:async';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Timer _timer;
int _start = 10;
void startTimer() {
const oneSec = const Duration(seconds: 1);
_timer = new Timer.periodic(
oneSec,
(Timer timer) => setState(() {
if (_start < 1) {
timer.cancel();
} else {
_start = _start - 1;
}
}));
}
Widget build(BuildContext context) {
return new Scaffold(
appBar: AppBar(title: Text("Timer test")),
body: Column(
children: <Widget>[
RaisedButton(
onPressed: () {
startTimer();
},
child: Text("start"),
),
Text("$_start")
],
));
}
}
Run Code Online (Sandbox Code Playgroud)
小智 8
我刚刚上传了这个包来实现这个: https: //pub.dev/packages/pausable_timer
// It starts paused
final timer = PausableTimer(Duration(seconds: 1), () => print('Fired!'));
timer.start();
timer.pause();
timer.start();
Run Code Online (Sandbox Code Playgroud)
Dart 本身也存在一个请求该功能的问题,但看起来不会很快添加。
| 归档时间: |
|
| 查看次数: |
6537 次 |
| 最近记录: |