Skip to content

Instantly share code, notes, and snippets.

@terryl1900
Last active July 26, 2022 15:36
Show Gist options
  • Save terryl1900/674e5985b03df48d739abcbb86917af3 to your computer and use it in GitHub Desktop.
Save terryl1900/674e5985b03df48d739abcbb86917af3 to your computer and use it in GitHub Desktop.
Counter app with a demo cubit implementation
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
// A counter app with a demo cubit implementation. The real cubit works
// slightly different, but this shows the gist.
// library.dart
class Cubit<T> {
Cubit(this.state) {
_controller.add(state);
}
T state;
final _controller = StreamController<T>(); // Need dispose this
Stream<T> stream() => _controller.stream;
void emit(T newState) {
state = newState;
_controller.add(state);
}
}
class CubitBuilder<T, C extends Cubit<T>> extends StatelessWidget {
const CubitBuilder({Key? key, required this.builder}) : super(key: key);
final AsyncWidgetBuilder<T> builder;
@override
Widget build(BuildContext context) {
return StreamBuilder<T>(
stream: context.read<C>().stream(),
builder: builder,
);
}
}
// counter.dart
class CounterCubit extends Cubit<int> {
CounterCubit(int initValue) : super(initValue);
void increment() => emit(state + 1);
void decrement() => emit(state - 1);
}
// main.dart
void main() {
runApp(Provider<CounterCubit>(
create: (context) => CounterCubit(0), child: const MyApp()));
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('Counter example')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
CubitBuilder<int, CounterCubit>(
builder: (context, snapshot) => Text('${snapshot.data}')),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
TextButton(
onPressed: () => context.read<CounterCubit>().increment(),
child: const Text('+1')),
TextButton(
onPressed: () => context.read<CounterCubit>().decrement(),
child: const Text('-1')),
],
),
],
),
),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment