gpt4 book ai didi

timer - 如何在 flutter 中从零开始计时?

转载 作者:IT王子 更新时间:2023-10-29 07:19:32 29 4
gpt4 key购买 nike

我试图显示一个计时器(格式 dd HH mm ss )来计算每个 Action 之间的时间(例如按钮 Action )。即使应用程序关闭并重建也需要工作。目前我加载了一个字符串日期,当我按下一个代表我按下按钮时间的按钮时,我用 sharedpreference 保存了日期。我格式化所有时间小数以比较和显示时差。我认为它不漂亮,不是我搜索的内容,而且我没有成功以 (dd HH mm ss) 格式显示时钟。如果有人有更简单的例子:)

load_records_pulsion() async{

/*var current_time = DateFormat('yyyy-MM-dd HH').format(DateTime.now());*/
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
RegExp regExp = new RegExp( //Here is the regex time pulsion
r"([12]\d{3})-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])",
);
last_pulsion = (prefs.getString('last_pulsion'))??0;


var match = regExp.firstMatch("$last_pulsion");
annees = match.group(1); // hh:mm
mois = match.group(2); // hh:mm
jours = match.group(3); // hh:mm

int annees_int = int.tryParse("$annees") ;
int mois_int = int.tryParse("$mois") ;
int jours_int = int.tryParse("$jours") ;
print("$annees_int");
print("$mois_int");
print("$jours_int");


final last_pulsion2 = DateTime(annees_int, mois_int, jours_int);
final date_now = DateTime.now();
difference_pulsion = date_now.difference(last_pulsion2).inDays;

if(difference_pulsion==0){
difference_pulsion ="";
prefix_pulsion ="Aujourd'hui";
}else{
prefix_pulsion ="jours";
}

});
}

我也试过这段代码,当我调用函数时定时器增加是可以的,但我不想要 datenow,我只需要从零开始

int _start = 0;
void startTimer() {
_start=0;
var now = new DateTime.now();
const oneSec = const Duration(seconds: 1);
_timer = new Timer.periodic(
oneSec,
(Timer timer) => setState(() {
{
chrono = now.add(new Duration(seconds: _start));
_start = _start + 1;
}
}));
}

编辑:我找到了这个解决方案,但有一些生命周期错误,如果我关闭应用程序,我就会失去计时器。

 Stopwatch stopwatch = new Stopwatch();


void rightButtonPressed() {
setState(() {
if (stopwatch.isRunning) {
stopwatch.reset();
} else {
stopwatch.reset();
stopwatch.start();
}
});
}
@override
Widget build(BuildContext context)
{
...
new Container(height: 80.0,
child: new Center(
child: new TimerText(stopwatch: stopwatch),
)),

...
class TimerText extends StatefulWidget {
TimerText({this.stopwatch});
final Stopwatch stopwatch;

TimerTextState createState() => new TimerTextState(stopwatch: stopwatch);
}

class TimerTextState extends State<TimerText> {

Timer timer;
final Stopwatch stopwatch;

TimerTextState({this.stopwatch}) {
timer = new Timer.periodic(new Duration(milliseconds: 30), callback);
}

void callback(Timer timer) {
if (stopwatch.isRunning) {
setState(() {

});
}
}

@override
Widget build(BuildContext context) {
final TextStyle timerTextStyle = const TextStyle(fontSize: 50.0, fontFamily: "Open Sans");
String formattedTime = TimerTextFormatter.format(stopwatch.elapsedMilliseconds);
return new Text(formattedTime, style: timerTextStyle);
}
}

class TimerTextFormatter {
static String format(int milliseconds) {

int seconds = (milliseconds / 1000).truncate();
int minutes = (seconds / 60).truncate();
int hours = (minutes / 60).truncate();
int days = (hours / 24).truncate();
String minutesStr = (minutes % 60).toString().padLeft(2, '0');
String secondsStr = (seconds % 60).toString().padLeft(2, '0');
String hoursStr = (hours % 60).toString().padLeft(2, '0');
String daysStr = (days % 24).toString().padLeft(2, '0');
return "$daysStr:$hoursStr:$minutesStr:$secondsStr";
}
}

最佳答案

如果您希望计数器在关闭应用程序后仍然存在,则无法将值保存在某处(例如共享首选项)。

使用 dateTime.toIso8601String() 和 DateTime.parse() 将使保存和加载不那么难看。要计算耗时,您可以使用 DateTime.now().difference(lastButtonPressed)

应该有一个函数来格式化 Duration ( https://api.flutter.dev/flutter/intl/DateFormat/formatDurationFrom.html ) 但它还没有实现。我在这里找到了一个:Formatting a Duration like HH:mm:ss

举个例子:

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutterfly/SharedPrefs.dart';

class TestWidget extends StatefulWidget {
@override
_TestWidgetState createState() => _TestWidgetState();
}

class _TestWidgetState extends State<TestWidget> {
DateTime _lastButtonPress;
String _pressDuration;
Timer _ticker;

@override
Widget build(BuildContext context) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text("Time since button pressed"),
Text(_pressDuration),
RaisedButton(
child: Text("Press me"),
onPressed: () {
_lastButtonPress = DateTime.now();
_updateTimer();
sharedPreferences.setString("lastButtonPress",_lastButtonPress.toIso8601String());
},
)
],
),
);
}


@override
void initState() {
super.initState();
final lastPressString = sharedPreferences.getString("lastButtonPress");
_lastButtonPress = lastPressString!=null ? DateTime.parse(lastPressString) : DateTime.now();
_updateTimer();
_ticker = Timer.periodic(Duration(seconds:1),(_)=>_updateTimer());
}


@override
void dispose() {
_ticker.cancel();
super.dispose();
}



void _updateTimer() {
final duration = DateTime.now().difference(_lastButtonPress);
final newDuration = _formatDuration(duration);
setState(() {
_pressDuration = newDuration;
});
}

String _formatDuration(Duration duration) {
String twoDigits(int n) {
if (n >= 10) return "$n";
return "0$n";
}

String twoDigitMinutes = twoDigits(duration.inMinutes.remainder(60));
String twoDigitSeconds = twoDigits(duration.inSeconds.remainder(60));
return "${twoDigits(duration.inHours)}:$twoDigitMinutes:$twoDigitSeconds";
}
}

为简单起见,我在全局范围内的 main 方法中初始化了共享首选项。 Example

关于timer - 如何在 flutter 中从零开始计时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56305911/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com