Skip to content

Instantly share code, notes, and snippets.

@abhaysood
Last active September 28, 2021 16:27
Show Gist options
  • Save abhaysood/2560a327ade58f87e5dfcd7ee57648b6 to your computer and use it in GitHub Desktop.
Save abhaysood/2560a327ade58f87e5dfcd7ee57648b6 to your computer and use it in GitHub Desktop.
Countdown Timer - Part 1
import 'dart:async';
import 'package:flutter/material.dart';
const Color darkBlue = Color.fromARGB(255, 18, 32, 47);
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.dark().copyWith(
scaffoldBackgroundColor: darkBlue,
),
debugShowCheckedModeBanner: false,
home: Home(),
);
}
}
class Home extends StatelessWidget {
@override
Widget build(BuildContext context) {
return const Scaffold(
body: Center(
child: Countdown(duration: Duration(seconds: 10)),
),
);
}
}
class Countdown extends StatefulWidget {
const Countdown({
Key? key,
required this.duration,
}) : super(key: key);
final Duration duration;
@override
State<Countdown> createState() => _CountdownState();
}
class _CountdownState extends State<Countdown> {
late int _counter;
late StreamSubscription _subscription;
String get _counterText => _counter.toString().padLeft(2, '0');
void _onTick(event) {
setState(() {
_counter = _counter - 1;
});
}
@override
void initState() {
_counter = widget.duration.inSeconds;
_subscription = Stream.periodic(const Duration(seconds: 1))
.take(widget.duration.inSeconds)
.listen(_onTick);
super.initState();
}
@override
void dispose() {
_subscription.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Text(
_counterText,
style: Theme.of(context).textTheme.headline2,
),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment