How to periodically set state?
As pskink and Günter mentioned, use a Timer
. You can even use the periodic
constructor that would fit well your scenario.
Note you don't need the asd()
function. When you call setState()
, the build
method will be called automatically passing the new now
property value.
If you want, use initState
to set an initial value and, as in this example, setup the Timer
.
import 'dart:async';import 'package:flutter/material.dart';void main() => runApp(MyApp());class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp(title: 'Timer Periodic Demo', home: RopSayac()); }}class RopSayac extends StatefulWidget { _RopSayacState createState() => _RopSayacState();}class _RopSayacState extends State<RopSayac> { String _now; Timer _everySecond; @override void initState() { super.initState(); // sets first value _now = DateTime.now().second.toString(); // defines a timer _everySecond = Timer.periodic(Duration(seconds: 1), (Timer t) { setState(() { _now = DateTime.now().second.toString(); }); }); } @override Widget build(BuildContext context) { return Container( child: Center( child: new Text(_now), ), ); }}
This recursive method should be enough for what you want. The seconds
set as 1 will keep triggering setState
each second, thus refreshing your widget tree.
void _timer() { Future.delayed(Duration(seconds: 1)).then((_) { setState(() { print("1 second closer to NYE!"); // Anything else you want }); _timer(); }); }
There's this excellent library called timer_builder. I think it'll help you out.
Example from the pub page:
import 'package:timer_builder/timer_builder.dart';class ClockWidget extends StatelessWidget { @override Widget build(BuildContext context) { return TimerBuilder.periodic(Duration(seconds: 1), //updates every second builder: (context) { return Text("${DateTime.now()}"); } ); }}