I'm trying to save information from a form to save a new "shopping list" and I get a ProviderNotFoundException error when trying to save. I have made the main page with the list of "shopping lists" and flutter-bloc with cubit and when I press add, it navigates me to another screen where I enter the name of the new list to register it. Should I pass the context to it when navigating? Why doesn't it grab the context if "CreateShopListFormView" is a child widget of HomeView?
In the ShopListsListView I have a BlocBuilder without a BlocProvider that generates and displays the list correctly.
The error it generates is this:
The following ProviderNotFoundException was thrown while handling a gesture:
Error: Could not find the correct Provider above this CreateShopListFormView Widget
HomeView (Main Window)
class HomeView extends StatelessWidget {
const HomeView({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MultiBlocProvider(
providers: [
BlocProvider<ShopListCubit>(create: (_) => ShopListCubit()..init())
],
child: Scaffold(
appBar: AppBar(
title: const Text('Shop List'),
),
body: const ShopListsListView(),
floatingActionButton: FloatingActionButton(
onPressed: () async {
Navigator.of(context).push(MaterialPageRoute(
builder: (context) => CreateShopListFormView(),
));
},
tooltip: 'Crear Lista de la compra',
child: const Icon(Icons.add),
),
));
}
}
ShopListCubit
class ShopListCubit extends Cubit<List<ShopList>> {
ShopListCubit() : super([]);
// final ShopListRepository _shopListRepository;
void init() {
//TODO: Call services
final list = List.generate(
10, (index) => ShopList(id: index, title: 'Shop list $index'));
emit(list);
}
void createShopList(ShopList shopList) async {
//TODO: call services
final list = state;
shopList.id = state.length + 1;
list.add(shopList);
emit(list);
}
}
ShopList class
class ShopList extends Equatable {
int id;
final String title;
ShopList({required this.id, required this.title});
@override
List<Object?> get props => [id];
}
It's a classic bug not only when using
Provider/flutter_bloc
, but also when trying to use things related to InheritedWidget.You can review this video to understand how the
InheritedWidgets
https://www.youtube.com/watch?v=57CCj9UH_Gw workThis is the graph of your widget tree.
You can see that the Cubit only covers the branch of the
HomeView
, since you created it there.That Provider/Bloc, is not available in the widget you open using the Navigator, since it is in a same level branch (unlike how you have it in the ShopListsListView, which belongs to the same tree/branch).
If you want the Cubit to be available, you would have to declare it above the
MaterialApp
, that way any widget/page you open will be able to access it. Otherwise you would have to use callbacks or return a value from the page you opened, in order to communicate with the previous widget and access the Cubit.