State Managementbeginner
Cubit Template
Complete Cubit pattern with states. Best practice for simple BLoC-lite state management.
#bloc#cubit#state-management
dart
| 1 | import 'package:flutter_bloc/flutter_bloc.dart'; |
| 2 | |
| 3 | // States |
| 4 | sealed class CounterState {} |
| 5 | class CounterInitial extends CounterState {} |
| 6 | class CounterLoading extends CounterState {} |
| 7 | class CounterLoaded extends CounterState { |
| 8 | final int count; |
| 9 | CounterLoaded(this.count); |
| 10 | } |
| 11 | class CounterError extends CounterState { |
| 12 | final String message; |
| 13 | CounterError(this.message); |
| 14 | } |
| 15 | |
| 16 | // Cubit |
| 17 | class CounterCubit extends Cubit<CounterState> { |
| 18 | CounterCubit() : super(CounterInitial()); |
| 19 | |
| 20 | void increment() { |
| 21 | final current = state; |
| 22 | if (current is CounterLoaded) { |
| 23 | emit(CounterLoaded(current.count + 1)); |
| 24 | } |
| 25 | } |
| 26 | |
| 27 | Future<void> load() async { |
| 28 | emit(CounterLoading()); |
| 29 | try { |
| 30 | await Future.delayed(const Duration(seconds: 1)); |
| 31 | emit(CounterLoaded(0)); |
| 32 | } catch (e) { |
| 33 | emit(CounterError(e.toString())); |
| 34 | } |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | // Usage in widget |
| 39 | class CounterPage extends StatelessWidget { |
| 40 | const CounterPage({super.key}); |
| 41 | |
| 42 | @override |
| 43 | Widget build(BuildContext context) { |
| 44 | return BlocProvider( |
| 45 | create: (_) => CounterCubit()..load(), |
| 46 | child: BlocBuilder<CounterCubit, CounterState>( |
| 47 | builder: (context, state) { |
| 48 | return switch (state) { |
| 49 | CounterInitial() => const CircularProgressIndicator(), |
| 50 | CounterLoading() => const CircularProgressIndicator(), |
| 51 | CounterLoaded(:final count) => Text('Count: $count'), |
| 52 | CounterError(:final message) => Text('Error: $message'), |
| 53 | }; |
| 54 | }, |
| 55 | ), |
| 56 | ); |
| 57 | } |
| 58 | } |