Want to periodically set state in flutter? 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | 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), ), ); } } |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.