I use Bloc (Cubit) for data management in my Flutter project. I get the following error in navigation operations.
BlocProvider.of() called with a context that does not contain a Bloc/Cubit of type CityCubit. No ancestor could be found starting from the context that was passed to BlocProvider.of().
When I go to my city list page from the login form, I get the above error. The error goes away when I refresh the project. Cities are listed. However, when I log in again and redirect me, I get an error.
main.dart --> MultiBlocProvider[providers: BlocProvider, BlocProvider]
With the help of the button "BlocProvider.of (context) .signIn (user);" logging in.
AutPage
BlocConsumer<AuthCubit, AuthState>(builder: (context, state) {
return _buildUI();
}, listener: (context, state) {
if (state is AuthLoading) {
return Center(
child: CircularProgressIndicator(),
);
}
if (state is AuthLoaded) {
Navigator.of(context).push(
MaterialPageRoute(builder: (context) => CityListPage()));
}
if (state is AuthError) {
Scaffold.of(context)
.showSnackBar(SnackBar(content: Text(state.message)));
print(state.message);
}
})
CityListPage
List<CityModel> cities = [];
@override
void initState() {
BlocProvider.of<CityCubit>(context).getAll();
super.initState();
}
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Hello"),
),
body: BlocConsumer<CityCubit, CityState>(builder: (context, state) {
if (state is CityInitial) {
return Text("....");
}
if (state is CityLoading) {
return Center(
child: CircularProgressIndicator(),
);
}
if (state is CitiesLoaded) {
cities.addAll(state.cities);
}
return _buildCities();
}, listener: (context, state) {
if (state is CityError) {
print("Error");
}
}));
}