I am trying to make a simple timer to know how much time has passed from a date to a current date
but the problem I have is that the Text widget is only painted once but it does not update, and I would like the text to update every 1 second. And not have to refresh the page, is it possible to do that?
import 'package:flutter/material.dart';
class TimerPage extends StatefulWidget {
@override
_TimerPageState createState() => _TimerPageState();
}
class _TimerPageState extends State<TimerPage> {
@override
Widget build(BuildContext context) {
final start = DateTime(2020, 8, 10, 16, 30, 0);
final currentdate= DateTime.now();
final comparation = currentdate.difference(start);
return Scaffold(
body: SafeArea(
child: Container(
padding: EdgeInsets.symmetric(vertical: 20),
child: Center(
child: Column(
children: <Widget>[
Text("Start time: " + start.toString()),
Divider(),
Text(
"time elapsed = " + comparation.toString().substring(0, 7),
style: TextStyle(color: Color(0xff5abd8c), fontSize: 26),
)
],
)),
),
),
);
}
}
I try this:
Timer timer;
final start = DateTime(2020, 8, 17, 21, 30, 0);
final dateActual = DateTime.now();
Duration comparation = new Duration(hours: 0, minutes: 0, seconds: 0);
@override
void initState() {
timer = Timer.periodic(Duration(seconds: 1), (_) {
setState(() {
comparation = dateActual.difference(start);
print(comparation);
});
});
}
@override
void dispose() {
timer?.cancel();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Container(
padding: EdgeInsets.symmetric(vertical: 20),
child: Center(
child: Column(
children: <Widget>[
Text("Start time: " + start.toString()),
Divider(),
Text(
"time elapsed = " + comparation.toString().substring(0, 7),
style: TextStyle(color: Color(0xff5abd8c), fontSize: 26),
)
],
)),
),
),
);
}
}