Skip to content

Instantly share code, notes, and snippets.

@maheshmnj
Created April 18, 2021 18:31
Show Gist options
  • Save maheshmnj/bd25ce561b06e61652910bbcafb35ba9 to your computer and use it in GitHub Desktop.
Save maheshmnj/bd25ce561b06e61652910bbcafb35ba9 to your computer and use it in GitHub Desktop.
Resuming futter lifecycle
import 'package:flutter/material.dart';
class CountdownTimer extends StatefulWidget {
@override
_CountdownTimerState createState() => _CountdownTimerState();
}
class _CountdownTimerState extends State<CountdownTimer>
with WidgetsBindingObserver, SingleTickerProviderStateMixin {
double countdownTime;
Duration _duration;
Animation _animation;
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
watch.start();
setState(() {
_duration = Duration(
days: 1); //Duration set to days 1 on initState for testing purposes
});
});
_animationController = AnimationController(
duration: Duration(seconds: 100),
vsync: this,
);
_animation = new CurvedAnimation(
parent: _animationController,
curve: Curves.linear,
)..addStatusListener((AnimationStatus status) {
if (status == AnimationStatus.completed) {
_animationController.reset();
_animationController.forward();
}
});
_animationController.forward();
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
//I want to update the timer when app is resumed
if (state == AppLifecycleState.resumed) {
print('App Resumed');
setState(() {
print('App life cycle resume duration $_duration}');
});
}
});
super.didChangeAppLifecycleState(state);
}
AnimationController _animationController;
Stopwatch watch = Stopwatch();
@override
Widget build(BuildContext context) {
print('Build run with duration $_duration');
return Container(
padding: const EdgeInsets.only(top: 10, bottom: 5),
child: Column(
children: [
Container(
width: 220,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text('DD', style: TextStyle(color: Colors.grey)),
Text('HH', style: TextStyle(color: Colors.grey)),
Text('MM', style: TextStyle(color: Colors.grey)),
Text('SS', style: TextStyle(color: Colors.grey)),
],
),
),
AnimatedBuilder(
animation: _animation,
builder: (_duration, Widget child) =>
Text(watch.elapsed.inSeconds.toString()))
],
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment