Sub topic 1
Why setState is not enough: ephemeral state vs app state
Prerequisites
This chapter assumes you know Dart classes, generics, async/await and null safety. You should also be comfortable with StatelessWidget, StatefulWidget, BuildContext and setState. You need the equatable and flutter_bloc packages in pubspec.yaml.
Ephemeral state and app state
Ephemeral state belongs to one widget, and no other widget reads it. A text field's cursor position or a button's pressed color are examples. setState handles this well.
App state is shared. A cart count, a signed-in user, or a todo list must be read by many widgets and must survive navigation. When these values live in StatefulWidgets, you pass them through constructors and callbacks, and rebuilds become hard to trace. Bloc and Cubit move this logic into plain Dart classes that the widget tree reads from.
Modeling immutable state with Equatable and copyWith
An immutable state object never changes after you create it. Equatable compares states by their field values, so two states with the same values count as equal. The copyWith method returns a new copy with some fields replaced.
import 'package:equatable/equatable.dart';
class CartState extends Equatable {
const CartState({this.itemCount = 0});
final int itemCount;
CartState copyWith({int? itemCount}) {
return CartState(itemCount: itemCount ?? this.itemCount);
}
@override
List<Object?> get props => [itemCount];
}Your first Cubit: state, emit and methods
A Cubit holds one state value. Its methods call emit to publish a new state.
import 'package:flutter_bloc/flutter_bloc.dart';
class CartCubit extends Cubit<CartState> {
CartCubit() : super(const CartState());
void addItem() => emit(state.copyWith(itemCount: state.itemCount + 1));
}Providing a Cubit with BlocProvider and reading it with context.read
BlocProvider creates the Cubit and makes it available to its descendant widgets. context.read returns the Cubit without subscribing to changes, so it suits calls inside button callbacks. The context in a widget's own build method sits above the provider, so the callback must run in a child widget.
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class CartPage extends StatelessWidget {
const CartPage({super.key});
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (_) => CartCubit(),
child: const CartView(),
);
}
}
class CartView extends StatelessWidget {
const CartView({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButton: FloatingActionButton(
onPressed: () => context.read<CartCubit>().addItem(),
child: const Icon(Icons.add),
),
);
}
}Exercise
Why does the button callback live in CartView instead of directly in CartPage's build method?
Show answer
The build context of CartPage sits above the BlocProvider, so context.read cannot find CartCubit from there. CartView sits below the provider, so its context can find the Cubit.