I'm trying to use Bloc package for my state management in my Flutter app. I have situation where I have two list within the same screen, and I am confused should I use two cubits for each list or I can make something like in code bellow where I used one cubit for both lists. I wanna know is this way of structuring code correct? In this image is the sketch of the screen.
abstract class CounterState extends Equatable {
const CounterState({this.valOne, this.valTwo, this.error});
final int? valOne;
final int? valTwo;
final String? error;
#override
List<Object?> get props => [valOne, valTwo, error];
}
class CounterInitial extends CounterState {}
class ValOneSuccess extends CounterState {
const ValOneSuccess(int? val, int? valTwo)
: super(valOne: val, valTwo: valTwo);
}
class ErrorState extends CounterState {
const ErrorState(int? val, int? valTwo, String error)
: super(valOne: val, valTwo: valTwo, error: error);
}
class CounterCubit extends Cubit<CounterState> {
CounterCubit() : super(CounterInitial());
void loadData() async {
int valOne;
int valTwo;
emit(CounterInitial());
try {
valOne = 2;
emit(ValOneSuccess(valOne, state.valTwo));
///If error is thrown
//throw Exception('ValueOne exception');
} catch (e) {
print(e);
emit(ErrorState(state.valOne, state.valTwo, e.toString()));
}
try {
valTwo = 1;
emit(ValOneSuccess(state.valOne, valTwo));
///If error is thrown
//throw Exception('ValueTwo exception');
} catch (e) {
state.error != null
? emit(ErrorState(
state.valOne, state.valTwo, 'Exception on both values'))
: emit(ErrorState(state.valOne, state.valTwo, e.toString()));
}
}
}
Related
For filter my list I use a state FilterState.
I have in this state my list filter but my widget for build list is not rebuild.
My print shows that the list is correct according to the state.
But GameList keeps its initial state which is not filtered : it's not rebuild.
Thanks,
my page for state :
BlocBuilder<GameBloc, GameState>(
builder: (context, state) {
if (state is LoadingState) {
return buildLoading();
} else if (state is FailState) {
return ErrorUI(message: state.message);
} else if (state is ListLoadedState) {
_list = state.list;
return GameList(list: state.list!);
} else if (state is FilterGamesState) {
print(state.list);
return GameList(list: state.list!);
}
return Container();
},
),
Bloc Page :
class GameBloc extends Bloc<GameEvent, GameState> {
GameBloc({required this.repository}) : super(LoadingState()) {
on<BackEvent>(_onBackEvent);
on<FetchGamesEvent>(_onFetchList);
on<FetchGameEvent>(_onFetchItem);
on<SavingEvent>(_onSavingEvent);
on<UpdateGameEvent>(_onUpdate);
on<CreateGameEvent>(_onCreate);
on<FilterGamesEvent>(_onFilter);
}
GameRepository repository;
final currentFilter = BehaviorSubject<Map<String, dynamic>>();
Future<void> _onFilter(
FilterGamesEvent event,
Emitter<GameState> emit,
) async {
try {
emit(LoadingState());
final list = event.list?.where((Game item) {
if (currentFilter.value.containsKey('player')) {
int players = currentFilter.value['player'].nb;
return players.isBetween(from: item.nopMin, to: item.nopMax);
}
return true;
}).where((Game item) {
if (currentFilter.value.containsKey('age')) {
return item.age!.isBetween(
from: currentFilter.value['age'].min,
to: currentFilter.value['age'].max);
}
return true;
}).where((Game item) {
if (currentFilter.value.containsKey('duration')) {
return compareToDuration(
item.durMin!,
item.durMax!,
currentFilter.value['duration'].min,
currentFilter.value['duration'].max);
}
return true;
}).where((Game item) {
if (currentFilter.value.containsKey('tags')) {
return item.tags!
.compareToList(currentFilter.value['tags'] as List<String>);
}
return true;
}).where((Game item) {
if (currentFilter.value.containsKey('collection')) {
return item.collection!
.compareToList(currentFilter.value['collection'] as List<String>);
}
return true;
}).toList();
emit(FilterGamesState(listGame: list!));
} catch (e) {
emit(const FailState(message: 'Failed to fetch all games data.'));
}
}
Event Page :
abstract class GameEvent extends Equatable {
final Game? item;
const GameEvent({this.item});
#override
List<Object> get props => [];
}
class InitialEvent extends GameEvent {
const InitialEvent({required Game item}) : super(item: item);
}
class BackEvent extends GameEvent {}
class SavingEvent extends GameEvent {}
class FetchGameEvent extends GameEvent {
const FetchGameEvent({required Game item}) : super(item: item);
}
class FetchGamesEvent extends GameEvent {}
class FilterGamesEvent extends GameEvent {
const FilterGamesEvent({required this.list});
final List<Game>? list;
}
State Page :
abstract class GameState extends Equatable {
final Game? item;
final List<Game>? list;
const GameState({this.item, this.list});
#override
List<Object> get props => [];
}
class GameInitial extends GameState {}
class FailState extends GameState {
const FailState({required this.message});
final String message;
}
class LoadingState extends GameState {}
class ListLoadedState extends GameState {
const ListLoadedState({required this.listGame}) : super(list: listGame);
final List<Game> listGame;
}
class ItemLoadedState extends GameState {
const ItemLoadedState({required this.game}) : super(item: game);
final Game game;
}
class FilterGamesState extends GameState {
const FilterGamesState({required this.listGame}) : super(list: listGame);
final List<Game> listGame;
}
I resolved this,
I send the key to GameList in FilterGameState.
else if (state is FilterGamesState) {
print(state.list);
return GameList(key: GlobalKey<GameFilterState>(), list: state.list!);
}
You are using Equatable but your props are empty. If you're using Equatable make sure to pass all properties to the props getter. (In both your state and event!)
Source: https://bloclibrary.dev/#/faqs?id=state-not-updating
The Flutter Todos Tutorial might also be helpful because it uses a filter too.
I am trying to fix an issue related to Flutter Bloc. I am editing someone else code to make it work with the latest flutter_bloc version but I am unable to do so. Can someone do a rewrite for my code so I can run it? I saw many answers but I am unable to understand how to fix my own code.
This is the complete code for all_categories_bloc.dart
class AllCategoriesBloc extends Bloc<AllCategoriesEvent, AllCategoriesState> {
AllCategoriesBloc({
this.apiRepository,
}) : super(AllCategoriesInitial()) {
on<GetAllCategories>(_onGetAllCategories);
}
final ApiRepository apiRepository;
Future<void> _onGetAllCategories(
GetAllCategories event,
Emitter<AllCategoriesState> emit,
) async {
try {
emit(const AllCategoriesLoading());
final categoriesModel = await apiRepository.fetchCategoriesList();
emit(AllCategoriesLoaded(categoriesModel));
if (categoriesModel.error != null) {
emit(AllCategoriesError(categoriesModel.error));
}
} catch (e) {
emit(
const AllCategoriesError(
"Failed to fetch all categories data. Is your device online ?",
),
);
}
}
}
Code for all_categories_event.dart
abstract class AllCategoriesEvent extends Equatable {
AllCategoriesEvent();
}
class GetAllCategories extends AllCategoriesEvent {
#override
List<Object> get props => null;
}
Code for all_categories_state.dart
abstract class AllCategoriesState extends Equatable {
const AllCategoriesState();
}
class AllCategoriesInitial extends AllCategoriesState {
AllCategoriesInitial();
#override
List<Object> get props => [];
}
class AllCategoriesLoading extends AllCategoriesState {
const AllCategoriesLoading();
#override
List<Object> get props => null;
}
class AllCategoriesLoaded extends AllCategoriesState {
final CategoriesModel categoriesModel;
const AllCategoriesLoaded(this.categoriesModel);
#override
List<Object> get props => [categoriesModel];
}
class AllCategoriesError extends AllCategoriesState {
final String message;
const AllCategoriesError(this.message);
#override
List<Object> get props => [message];
}
It throws an error "Bad state: add(GetAllCategories) was called without a registered event handler.
Make sure to register a handler via on((event, emit) {...})"
I have this add(GetAllCategories) in my home. dart file but the solution is to edit this code which I am unable to do so. Can someone do a rewrite for the latest bloc? I would be thankful.
Let's get through the migration guide step by step:
package:bloc v5.0.0: initialState has been removed. For more information check out #1304.
You should simply remove the AllCategoriesState get initialState => AllCategoriesInitial(); portion from your BLoC.
package:bloc v7.2.0 Introduce new on<Event> API. For more information, read the full proposal.
As a part of this migration, the mapEventToState method was removed, each event is registered in the constructor separately with the on<Event> API.
First of all, register your events in the constructor:
AllCategoriesBloc() : super(AllCategoriesInitial()) {
on<GetAllCategories>(_onGetAllCategories);
}
Then, create the _onGetAllCategories method:
Future<void> _onGetAllCategories(
GetAllCategories event,
Emitter<AllCategoriesState> emit,
) async {
try {
emit(const AllCategoriesLoading());
final categoriesModel = await _apiRepository.fetchCategoriesList();
emit(AllCategoriesLoaded(categoriesModel));
if (categoriesModel.error != null) {
emit(AllCategoriesError(categoriesModel.error));
}
} catch (e) {
emit(
const AllCategoriesError(
"Failed to fetch all categories data. Is your device online ?",
),
);
}
}
Notice, that instead of using generators and yielding the next state, you should use the Emitter<AllCategoriesState> emitter.
Here is the final result of the migrated AllCategoriesBloc:
class AllCategoriesBloc extends Bloc<AllCategoriesEvent, AllCategoriesState> {
AllCategoriesBloc() : super(AllCategoriesInitial()) {
on<GetAllCategories>(_onGetAllCategories);
}
final ApiRepository _apiRepository = ApiRepository();
Future<void> _onGetAllCategories(
GetAllCategories event,
Emitter<AllCategoriesState> emit,
) async {
try {
emit(const AllCategoriesLoading());
final categoriesModel = await _apiRepository.fetchCategoriesList();
emit(AllCategoriesLoaded(categoriesModel));
if (categoriesModel.error != null) {
emit(AllCategoriesError(categoriesModel.error));
}
} catch (e) {
emit(
const AllCategoriesError(
"Failed to fetch all categories data. Is your device online ?",
),
);
}
}
}
Bonus tip
Instead of creating an instance of ApiRepository inside the BLoC directly, you can use the constructor injection:
class AllCategoriesBloc extends Bloc<AllCategoriesEvent, AllCategoriesState> {
AllCategoriesBloc({
required this.apiRepository,
}) : super(AllCategoriesInitial()) {
on<GetAllCategories>(_onGetAllCategories);
}
final ApiRepository apiRepository;
...
}
Now, when creating BLoC, pass the instance of the repository to the constructor, like AllCategoriesBloc(apiRepository: ApiRepository()). This way you will be able to properly unit test your BLoC by mocking dependencies (in this case, ApiRepository).
I am new in this state management world. So I was trying to follow this tutorial (How to Save Products in a Wishlist using the BloC Pattern - EP10 - The eCommerce Series), but mapEventToState is deprecated so I am not sure what to do.
Here is my state:
part of 'wishlist_bloc.dart';
abstract class WishlistState extends Equatable {
const WishlistState();
#override
List<Object> get props => [];
}
class WishlistLoading extends WishlistState {}
class WishlistLoaded extends WishlistState {
final WishlistModel wishlist;
const WishlistLoaded({this.wishlist = const WishlistModel()});
#override
List<Object> get props => [wishlist];
}
class WishlistError extends WishlistState {}
Here is my event:
part of 'wishlist_bloc.dart';
abstract class WishlistEvent extends Equatable {
const WishlistEvent();
#override
List<Object> get props => [];
}
class StartWishlist extends WishlistEvent {}
class AddWishlistProduct extends WishlistEvent {
final ProductModel product;
const AddWishlistProduct(this.product);
#override
List<Object> get props => [product];
}
class RemoveWishlistProduct extends WishlistEvent {
final ProductModel product;
const RemoveWishlistProduct(this.product);
#override
List<Object> get props => [product];
}
Here is my bloc:
import '../models/product_model.dart';
import '../models/wishlist_model.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:equatable/equatable.dart';
part 'wishlist_event.dart';
part 'wishlist_state.dart';
class WishlistBloc extends Bloc<WishlistEvent, WishlistState> {
WishlistBloc() : super(WishlistLoading()) {
on<StartWishlist>(_mapStartWishlistToState);
on<AddWishlistProduct>(_mapAddWishlistToState);
on<RemoveWishlistProduct>(_mapRemoveWishlistToState);
}
void _mapStartWishlistToState(event, emit) async {
emit(WishlistLoading());
try {
await Future.delayed(Duration(seconds: 1));
emit(WishlistLoaded());
} catch (_) {}
}
// Error ...
void _mapAddWishlistToState(event, emit) async {
if (state is WishlistLoaded) {
try {
emit(WishlistLoaded(
wishlist: WishlistModel(
products: List.from(state.wishlist.products)
..add(event.product))));
} catch (_) {}
}
}
void _mapRemoveWishlistToState(event, emit) async {}
}
But I get this error instead: "The getter 'wishlist' isn't defined for the type 'WishlistState'. Try importing the library that defines 'wishlist', correcting the name to the name of an existing getter, or defining a getter or field name 'wishlist'".
How to access 'wishlist' in the new version of flutter_bloc? Thank you.
Try to define arguments types while difining the functions. So your updated code would look like this:
import '../models/product_model.dart';
import '../models/wishlist_model.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:equatable/equatable.dart';
part 'wishlist_event.dart';
part 'wishlist_state.dart';
class WishlistBloc extends Bloc<WishlistEvent, WishlistState> {
WishlistBloc() : super(WishlistLoading()) {
on<StartWishlist>(_mapStartWishlistToState);
on<AddWishlistProduct>(_mapAddWishlistToState);
on<RemoveWishlistProduct>(_mapRemoveWishlistToState);
}
void _mapStartWishlistToState(
// Added argument types below
StartWishlist event, Emitter<WishlistState> emit) async {
emit(WishlistLoading());
try {
await Future.delayed(Duration(seconds: 1));
emit(WishlistLoaded());
} catch (_) {}
}
void _mapAddWishlistToState(
// Added argument types below
AddWishlistProduct event, Emitter<WishlistState> emit) async {
if (state is WishlistLoaded) {
try {
emit(WishlistLoaded(
wishlist: WishlistModel(
products: List.from(state.wishlist.products)
..add(event.product))));
} catch (_) {}
}
}
void _mapRemoveWishlistToState(
// Added argument types below
RemoveWishlistProduct event, Emitter<WishlistState> emit) async {}
}
Type promotion is impossible for properties, since they can potentially return different values each time they are called. As such, it is impossible for the compiler to know that the state getter will return a WishlistLoaded instance, even after knowing that the same getter returned a WishlistLoaded four lines earlier.
One way around this is to assign the state to a local variable, which is eligible for type promotion.
void _mapAddWishlistToState(AddWishlistProduct event, Emitter<WishlistState> emit) async {
final state = this.state; // local variable
if (state is WishlistLoaded) {
try {
emit(WishlistLoaded(
wishlist: WishlistModel(
products: List.from(state.wishlist.products)
..add(event.product))));
} catch (_) {}
}
}
The linked video used a parameter, which is also eligible for type promotion. If it had used the state getter directly in _mapAddWishlistProductToState, it would have run into the same error.
You just need to cast your state as following
void _mapAddWishlistToState(event, emit) async {
if (state is WishlistLoaded) {
try {
emit(WishlistLoaded(
wishlist: WishlistModel(
products: List.from((state as WishlistLoaded).wishlist.products)
..add(event.product))));
} catch (_) {}
}
}
I just started learning bloc and I'm trying to make a cart bloc but I'm getting a state error:
Error: Unhandled error Expected a value of type 'CartSuccess', but got one of type 'CartLoading' occurred in bloc Instance of 'CartBloc'.
Even if I delete the yield CartLoading(), the error change to:
Error: Unhandled error Expected a value of type 'CartSuccess', but got one of type 'CartInitial' occurred in bloc Instance of 'CartBloc'.
Cart State
abstract class CartState extends Equatable {
const CartState();
#override
List<Object> get props => [];
}
class CartInitial extends CartState {}
class CartLoading extends CartState {}
class CartSuccess extends CartState {
final List<ProductModel> carts;
const CartSuccess(this.carts);
#override
List<Object> get props => [carts];
}
class CartFailed extends CartState {}
Cart Event
abstract class CartEvent extends Equatable {
const CartEvent();
#override
List<Object> get props => [];
}
class FetchCart extends CartEvent {}
class AddToCart extends CartEvent {
final ProductModel product;
const AddToCart(this.product);
#override
List<Object> get props => [product];
}
class RemoveFromCart extends CartEvent {
final ProductModel product;
const RemoveFromCart(this.product);
#override
List<Object> get props => [product];
}
Cart Bloc
class CartBloc extends Bloc<CartEvent, CartState> {
CartBloc() : super(CartInitial());
#override
Stream<CartState> mapEventToState(CartEvent event) async* {
yield CartLoading();
if(event is FetchCart){
final List<ProductModel> carts = List.from((state as CartSuccess).carts);
yield CartSuccess(carts);
}
if(event is AddToCart){
try{
final List<ProductModel> carts = List.from((state as CartSuccess).carts)
..add(event.product);
yield CartSuccess(carts);
}catch(e){
yield CartFailed();
print(e);
}
}
if(event is RemoveFromCart){
try{
final carts = (state as CartSuccess)
.carts
.where((product) => product.id != event.product.id)
.toList();
yield CartSuccess(carts);
}catch(e){
yield CartFailed();
print(e);
}
}
}
}
I guess this comes from here: List.from((state as CartSuccess).carts). You yield yield CartLoading();before this, so your state is no longer CartSuccess but CartLoading. You previous CartSuccess state was lost with yielding CartLoading
I am using flutter_bloc in my application and referring to this sample. Now when I am running my application it gives me an error saying:
flutter: type 'MovieUninitialized' is not a subtype of type
'MovieLoaded' in type cast
My bloc contains three files: movie_state, movie_event, and movie_bloc
movie_state.dart
import 'package:equatable/equatable.dart';
import 'package:movie_project/models/movie.dart';
abstract class MovieState extends Equatable {
MovieState([List props = const []]) : super(props);
}
class MovieUninitialized extends MovieState {
#override
String toString() => 'MovieUninitialized';
}
class MovieError extends MovieState {
#override
String toString() => 'MovieError';
}
class MovieLoaded extends MovieState {
final List<Movie> movies;
final bool hasReachedMax;
// Keeps track of the page to fetch the latest movies from the api
final latestMoviesPage;
MovieLoaded({
this.movies,
this.hasReachedMax,
this.latestMoviesPage,
}) : super([movies, hasReachedMax, latestMoviesPage]);
MovieLoaded copyWith({
List<Movie> movies,
bool hasReachedMax,
int latestMoviesPage,
}) {
return MovieLoaded(
movies: movies ?? this.movies,
hasReachedMax: hasReachedMax ?? this.hasReachedMax,
latestMoviesPage: this.latestMoviesPage,
);
}
#override
String toString() =>
'PostLoaded { posts: ${movies.length}, hasReachedMax: $hasReachedMax }';
}
movie_event.dart
import 'package:equatable/equatable.dart';
abstract class MovieEvent extends Equatable {}
class Fetch extends MovieEvent {
#override
String toString() => 'Fetch';
}
movie_bloc.dart
class MovieBloc extends Bloc<MovieEvent, MovieState> {
final MovieRepository movieRepository;
MovieBloc({#required this.movieRepository});
#override
Stream<MovieState> transform(
Stream<MovieEvent> events,
Stream<MovieState> Function(MovieEvent event) next,
) {
return super.transform(
(events as Observable<MovieEvent>).debounceTime(
Duration(milliseconds: 500),
),
next,
);
}
#override
MovieState get initialState => MovieUninitialized();
#override
Stream<MovieState> mapEventToState(MovieEvent event) async* {
if (event is Fetch && !_hasReachedMax(currentState)) {
try {
if (currentState is MovieUninitialized) {
final movies = await movieRepository.fetchMovies(1);
yield MovieLoaded(
movies: movies,
hasReachedMax: false,
latestMoviesPage:
(currentState as MovieLoaded).latestMoviesPage + 1,
);
return;
}
if (currentState is MovieLoaded) {
final movies = await movieRepository
.fetchMovies((currentState as MovieLoaded).latestMoviesPage);
yield movies.isEmpty
? (currentState as MovieLoaded).copyWith(hasReachedMax: true)
: MovieLoaded(
movies: (currentState as MovieLoaded).movies + movies,
hasReachedMax: false,
latestMoviesPage:
(currentState as MovieLoaded).latestMoviesPage + 1,
);
}
} catch (_) {
print(_);
yield MovieError();
}
}
}
bool _hasReachedMax(MovieState state) =>
state is MovieLoaded && state.hasReachedMax;
}
I need to increment the latestMoviesPage until it reaches the max limit. If I remove latestMoviesPage from my bloc code issue gets resolves but I really need it to load more pages.
Instead of
latestMoviesPage: (currentState as MovieLoaded).latestMoviesPage + 1,
I need to write:
latestMoviesPage: 2,