Search code examples
flutterflutter-provider

Could not find the correct Provider<Cart> above this DetailsScreen Widget


I get the following error: Could not find the correct Provider above this ProductDetailsScreen Widget

This happens because you used a BuildContext that does not include the provider of your choice. There are a few common scenarios:

My code:

    class Cart extends ChangeNotifier {
  final List<Product> _list = [];
  List<Product> get getItems {
    return _list;
  }

  icon: Badge(
                          showBadge: context.read<Cart>().getItems.isEmpty
                              ? false
                              : true,
                          padding: const EdgeInsets.all(2),
                          badgeColor: Colors.yellow,
                          badgeContent: Text(
                            context
                                .watch<Cart>()
                                .getItems
                                .length
                                .toString(),
                            style: const TextStyle(
                                fontSize: 16, fontWeight: FontWeight.w600),
                          ),
                          child: const Icon(Icons.shopping_cart))),

any help appreciated


Solution

  • You need to include your Cart provider in your runApp function in main. It should look something like this:

    void main() {
        runApp(MultiProvider(
            providers: [
                Provider<Cart>(create: (context) => CartProvider()),
                // add all providers in a list
            ], 
            child: const MyApp(), 
        ));
    }
    

    It has to be initalized before you build the widget that needs it.