Skip to content

Instantly share code, notes, and snippets.

@chimon2000
Created May 9, 2022 07:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chimon2000/e4f8e04dbd7da660aea76f26393ca3a9 to your computer and use it in GitHub Desktop.
Save chimon2000/e4f8e04dbd7da660aea76f26393ca3a9 to your computer and use it in GitHub Desktop.
Riverpod Countdown
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
void main() {
runApp(const ProviderScope(child: MyApp()));
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const HomePage(),
);
}
}
class HomePage extends ConsumerWidget {
const HomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context, WidgetRef ref) {
final countdown = ref.watch(countdownProvider(15));
return Material(
child: Center(
child: countdown.maybeWhen(
data: (data) => Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('${data.tick}'),
Text('${data.countdownState}'),
],
),
orElse: () => Container(),
),
),
);
}
}
final countdownProvider =
StreamProvider.family.autoDispose<Countdown, int>((ref, limit) {
final stream = Stream<int>.periodic(
const Duration(seconds: 1),
(number) => limit - number,
).takeWhile((tick) => tick >= 0).map<Countdown>(
(tick) => Countdown(
tick: tick,
countdownState:
tick > 0 ? CountdownState.inProgress : CountdownState.finished,
),
);
return stream;
});
class Countdown {
const Countdown({
required this.tick,
required this.countdownState,
});
final int tick;
final CountdownState countdownState;
@override
bool operator ==(Object other) {
if (identical(this, other)) return true;
return other is Countdown &&
other.tick == tick &&
other.countdownState == countdownState;
}
@override
int get hashCode => tick.hashCode ^ countdownState.hashCode;
}
enum CountdownState { inProgress, finished }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment