Last active
December 7, 2020 04:57
-
-
Save willyliu/3ceab3d1b1947e8e3ae4f7d5ea89c5a8 to your computer and use it in GitHub Desktop.
Flutter countdown widget in StatefulBuilder. Will receive exception if user go back before countdown finished.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:async'; | |
import 'package:flutter/material.dart'; | |
void main() { | |
runApp(MaterialApp(title: 'Timer in StatefulBuilder', home: FirstRoute())); | |
} | |
class FirstRoute extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
appBar: AppBar( | |
title: Text("First Route"), | |
), | |
body: Center( | |
child: ElevatedButton( | |
child: Text('Countdown'), | |
onPressed: () { | |
Navigator.push( | |
context, | |
MaterialPageRoute(builder: (context) => SecondRoute()), | |
); | |
}))); | |
} | |
} | |
class SecondRoute extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
appBar: AppBar( | |
title: Text("Second Route"), | |
), | |
body: Center( | |
child: Column( | |
mainAxisAlignment: MainAxisAlignment.center, | |
crossAxisAlignment: CrossAxisAlignment.center, | |
children: [ | |
ElevatedButton( | |
onPressed: () { | |
Navigator.pop(context); | |
}, | |
child: Text('Go back!'), | |
), | |
CountdownWidget(), | |
]))); | |
} | |
} | |
class CountdownWidget extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
int countdown = 10; | |
return StatefulBuilder(builder: (context, setState) { | |
if (countdown > 0) { | |
Timer(Duration(seconds: 1), () { | |
setState(() { | |
countdown--; | |
}); | |
}); | |
} | |
return Text(countdown.toString()); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment