smladeoye / flutter-simple-timer

A Simple Flutter Timer Widget with various customizable features.
MIT License
19 stars 7 forks source link

Run timer automatically as page is navigated to #9

Closed vegeta-ssaiyan closed 3 years ago

vegeta-ssaiyan commented 3 years ago

Hi Adeoye, thanks for your fast reply in the previous issue I closed. Also, thanks for creating this really nice and simple timer too.!

I'm pretty new to Flutter. Have to consult you ><

How do I automatically start the timer once user reaches the page? The example code provided has functions encoded in buttons to start stop reset. However I would like to make the start function begin as soon as user reaches the page and stops as user leaves the page. Also, it would be good to print the amount of time users have spent on the page.

`class _TimerPageState extends State with SingleTickerProviderStateMixin { TimerController _timerController; TimerStyle _timerStyle = TimerStyle.ring; TimerProgressIndicatorDirection _progressIndicatorDirection = TimerProgressIndicatorDirection.clockwise; TimerProgressTextCountDirection _progressTextCountDirection = TimerProgressTextCountDirection.count_up;

@override void initState() { _timerController = TimerController(this); super.initState(); }

@override Widget build(BuildContext context) { return Scaffold( backgroundColor: Color(0xff04072E), appBar: AppBar( title: Text('Timer', style: TextStyle(color: Colors.white)), backgroundColor: Color(0xff04072E), ), body: SafeArea( child: SingleChildScrollView( child: Column(children: [ Container( margin: EdgeInsets.symmetric(vertical: 10), child: SimpleTimer( controller: _timerController, timerStyle: _timerStyle, duration: const Duration(seconds: 0), displayProgressIndicator: false, backgroundColor: Colors.grey, progressTextStyle: TextStyle(color: Colors.white, fontSize: 60), ), ), ]), ), ); } }`

smladeoye commented 3 years ago

From your sample code, I can see you are using the TimerController. You can start the timer immediately after it is loaded by simply calling the start() on the _timerController. Also just saw your comment in the other pull-request and your stackoverflow post.

You are calling the start() method in the initState method - at this point the widget has not been built/loaded. You can call the method immediately after the widget is first loaded by making use of the addPostFrameCallback() like below:

WidgetsBinding.instance.addPostFrameCallback((_) { _timerController.start(); })