I'm new to Flutter and I want to know if is possible to pass an initial value for a parameter of a Initial State while in state management:
This is my "Initial State":
class HomeInitialState extends HomeCubitState {
final List<RecipeEntity> recipes;
const HomeInitialState({required this.recipes});
@override
List<Object?> get props => [recipes];
}
On my Cubit I initialize my HomeInitialState with super constructor:
class HomeCubit extends Cubit<HomeCubitState> {
HomeCubit({required this.homeUseCase}) : super(HomeInitialState());
final HomeUseCase homeUseCase;
late List<RecipeEntity> receitas;
void filterEvent(String tipo, BuildContext context) async {
emit(HomeFilteredState(
receitasFiltradas: [
RecipeEntity(id: 2, nome: 'Lasanha', tempoPreparo: 60, tipo: 'Salgado', imagem: Image.asset('assets/images/lasanha.png', width: MediaQuery.of(context).size.width * 0.30))
],
tipoFiltrado: tipo
));
}
String _mapFailureToMessage(Failure failure) {
switch (failure.runtimeType) {
case ServerFailure:
return serverFailureMessage;
case CacheFailure:
return cacheFailureMessage;
default: return generalFailureMessage;
}
}
}
I need to initialize with my "recipes" list full
You can use factory constructor to your state like this:
class HomeInitialState extends HomeCubitState {
final List<RecipeEntity> recipes;
const HomeInitialState({required this.recipes});
factory HomeInitialState.initial() => HomeInitialState(
recipes: _yourInitData(),
);
@override
List<Object?> get props => [recipes];
}
Then at your BlocProvider in your UI:
BlocProvider<HomeInitialBloc>(
create: (context) => HomeInitialBloc(HomeInitialState.initial()),
child: ...,
)