#dart #flutter
#дротик #трепещущий
Вопрос:
Я играл с классом Dart Timer, чтобы заставить его работать в самой простой форме, однако я застрял, пытаясь добавить к нему функцию паузы. Я просмотрел их документацию, но в них мало информации об их классе 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")
],
));
}
}
Ответ №1:
Я только что загрузил этот пакет, чтобы реализовать именно это:https://pub.dev/packages/pausable_timer
// It starts paused
final timer = PausableTimer(Duration(seconds: 1), () => print('Fired!'));
timer.start();
timer.pause();
timer.start();
Также существует проблема с запросом функции в самом Dart, но не похоже, что она будет добавлена в ближайшее время.
Комментарии:
1. В моем случае я хочу, чтобы
timer
запускался каждые 1 секунду и зависал, когда я захочу, но я понял, что ваша библиотека работает только для запуска кода по истечении определенного времени2. Все, что вам нужно сделать, это использовать
timer.reset(); timer.start();
в обратном вызове таймера, чтобы запустить его снова (сделайте его периодическим). Вот пример того, как с его помощью реализовать обратный отсчет, который является тем же, что вы хотите, за исключением того, что таймер завершится после ряда повторений: pub.dev/packages/…
Ответ №2:
Встроенной pause
функции нет, поскольку Timer
класс в основном предназначен для планирования блоков кода на потом.
Каков ваш вариант использования? Stopwatch
Класс имеет функцию приостановки и возобновления.
Ответ №3:
Ниже приведен пример рабочего флаттера с паузой и вибрациями (источник)
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:vibration/vibration.dart';
void main() => runApp(MaterialApp(home: CountdownCard()));
class CountdownCard extends StatefulWidget {
// This widget is the root of your application.
@override
_CountdownCardState createState() => _CountdownCardState();
}
class _CountdownCardState extends State<CountdownCard> {
Timer _timer;
int _start = 0;
bool _vibrationActive = false;
void startTimer(int timerDuration) {
if (_timer != null) {
_timer.cancel();
cancelVibrate();
}
setState(() {
_start = timerDuration;
});
const oneSec = const Duration(seconds: 1);
print('test');
_timer = new Timer.periodic(
oneSec,
(Timer timer) => setState(
() {
if (_start < 1) {
timer.cancel();
print('alarm');
vibrate();
} else {
_start = _start - 1;
}
},
),
);
}
void cancelVibrate() {
_vibrationActive = false;
Vibration.cancel();
}
void vibrate() async {
_vibrationActive = true;
if (await Vibration.hasVibrator()) {
while (_vibrationActive) {
Vibration.vibrate(duration: 1000);
await Future.delayed(Duration(seconds: 2));
}
}
}
void pauseTimer() {
if (_timer != null) _timer.cancel();
}
void unpauseTimer() => startTimer(_start);
@override
void dispose() {
_timer.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Countdown'),
),
body: Wrap(children: <Widget>[
Column(
children: <Widget>[
RaisedButton(
onPressed: () {
startTimer(10);
},
child: Text("start"),
),
Text("$_start"),
RaisedButton(
onPressed: () {
pauseTimer();
},
child: Text("pause"),
),
RaisedButton(
onPressed: () {
unpauseTimer();
},
child: Text("unpause"),
),
RaisedButton(
onPressed: () {
cancelVibrate();
},
child: Text("stop alarm"),
),
],
),
]));
}
}
Ответ №4:
переменные, которые мы определяем, запускают таймер при открытии страницы. таймер отключается при закрытии страницы.
при касании экрана переменная длительность становится истинной, и таймер прекращает обратный отсчет
Timer? _timer;
int _start = 200;
bool duration = false;
Duration oneSec = const Duration(milliseconds: 10);
@override
void initState() {
// TODO: implement initState
super.initState();
startTimer();
}
@override
void dispose() {
_timer!.cancel();
super.dispose();
}
```
GestureDetector(
onTap: () {},
onTapDown: (e) {
setState(() {
duration = true;
});
},
onHorizontalDragEnd: (e) {
Navigator.pop(context);
},
onTapUp: (e) {
setState(() {
duration = false;
});
},
child:Text("demo page")}
void startTimer() {
_timer = new Timer.periodic(
oneSec,
(Timer timer) {
if (_start == 0) {
setState(() {
timer.cancel();
Navigator.pop(context);
});
} else {
setState(() {
duration == false ? _start-- : null;
});
}
},
);
}
}