Skip to content

Instantly share code, notes, and snippets.

@abhaysood
Created September 28, 2021 16:29
Show Gist options
  • Save abhaysood/14d97a741eaad965e069c561a5f4d404 to your computer and use it in GitHub Desktop.
Save abhaysood/14d97a741eaad965e069c561a5f4d404 to your computer and use it in GitHub Desktop.
Countdown Timer - Part 2
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/semantics.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),
semanticsAnnouncementInterval: Duration(seconds: 5),
),
),
);
}
}
class Countdown extends StatefulWidget {
const Countdown({
Key? key,
required this.duration,
required this.semanticsAnnouncementInterval,
}) : super(key: key);
final Duration duration;
final Duration semanticsAnnouncementInterval;
@override
State<Countdown> createState() => _CountdownState();
}
class _CountdownState extends State<Countdown> {
late int _timeLeftInSeconds;
late StreamSubscription _subscription;
bool _hasAccessibilityFocus = false;
String get _counterText => _timeLeftInSeconds.toString().padLeft(2, '0');
bool get _shouldMakeAnnouncement =>
_timeLeftInSeconds % widget.semanticsAnnouncementInterval.inSeconds ==
0 &&
_hasAccessibilityFocus;
void _onTick(event) {
setState(() {
_timeLeftInSeconds = _timeLeftInSeconds - 1;
});
if (_shouldMakeAnnouncement) {
_makeSemanticsAnnouncement();
}
}
void _makeSemanticsAnnouncement() {
SemanticsService.announce(
"$_timeLeftInSeconds seconds left",
TextDirection.ltr,
);
}
@override
void initState() {
_timeLeftInSeconds = widget.duration.inSeconds;
_subscription = Stream.periodic(const Duration(seconds: 1))
.take(widget.duration.inSeconds)
.listen(_onTick);
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Semantics(
onDidGainAccessibilityFocus: () => _hasAccessibilityFocus = true,
onDidLoseAccessibilityFocus: () => _hasAccessibilityFocus = false,
child: ExcludeSemantics(
child: Text(
_counterText,
style: Theme.of(context).textTheme.headline2,
),
),
),
),
);
}
@override
void dispose() {
_subscription.cancel();
super.dispose();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment