Created
December 7, 2020 04:34
-
-
Save willyliu/80075428923078c64fccf211de20ffc0 to your computer and use it in GitHub Desktop.
Flutter countdown stateful widget
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: 'Countdown Timer', 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(10), | |
]))); | |
} | |
} | |
class CountdownWidget extends StatefulWidget { | |
final int _countdown; | |
CountdownWidget(this._countdown); | |
@override | |
_CountdownWidgetState createState() => _CountdownWidgetState(this._countdown); | |
} | |
class _CountdownWidgetState extends State<CountdownWidget> { | |
Timer _timer; | |
int _countdown; | |
_CountdownWidgetState(this._countdown); | |
@override | |
void initState() { | |
_timer = Timer.periodic(Duration(seconds: 1), (timer) { | |
if (_countdown <= 0) { | |
timer.cancel(); | |
return; | |
} | |
setState(() { | |
_countdown--; | |
}); | |
}); | |
super.initState(); | |
} | |
@override | |
void dispose() { | |
_timer?.cancel(); | |
super.dispose(); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return Text(_countdown.toString()); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment