ProviderNotFoundException was thrown building Consumer(dirty): Error: Could not find the correct Provider above this Consumer Widget

Viewed 613

I'm new to Flutter and I'm trying to use providers to manage the state of my app but I get this error:

══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════ The following ProviderNotFoundException was thrown building Consumer(dirty): Error: Could not find the correct Provider above this Consumer Widget

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

  • You added a new provider in your main.dart and performed a hot-reload. To fix, perform a hot-restart.

  • The provider you are trying to read is in a different route.

    Providers are "scoped". So if you insert of provider inside a route, then other routes will not be able to access that provider.

  • You used a BuildContext that is an ancestor of the provider you are trying to read.

    Make sure that Consumer is under your MultiProvider/Provider. This usually happens when you are creating a provider and trying to read it immediately.

    For example, instead of:

    Widget build(BuildContext context) {
      return Provider<Example>(
        create: (_) => Example(),
        // Will throw a ProviderNotFoundError, because `context` is associated
        // to the widget that is the parent of `Provider<Example>`
        child: Text(context.watch<Example>()),
      ),
    }
    

    consider using builder like so:

    Widget build(BuildContext context) {
      return Provider<Example>(
        create: (_) => Example(),
        // we use `builder` to obtain a new `BuildContext` that has access to the provider
        builder: (context) {
          // No longer throws
          return Text(context.watch<Example>()),
        }
      ),
    }
    

Here is my main.dart:

import 'package:app_alimentazione/Pagine/pagina_alimenti.dart';
import 'package:app_alimentazione/Providers/json_list_provider.dart';
import 'package:app_alimentazione/Providers/lists_provider.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'Pagine/pagina_principale.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        FutureProvider(
            create: (context) => JsonListProvider().jsonData,
            initialData: []),
        ChangeNotifierProvider(create: (_) => ListsProvider())
      ],
      builder: (context, child) {

          return Consumer<JsonListProvider>(
            builder: (context, jsonList, child){ 
            return MaterialApp(
              theme: ThemeData(
                primarySwatch: Colors.blue,
              ),
              home: PaginaAlimenti(jsonList:jsonList.jsonData),
            );}
          );
     
      },
    );
  }
}

And here is my FirstPage:

import 'package:app_alimentazione/Classi/alimento.dart';
import 'package:app_alimentazione/Providers/lists_provider.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class PaginaAlimenti extends StatelessWidget {
  final Future<List<Alimento>>? jsonList;
  const PaginaAlimenti({Key? key, this.jsonList}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Consumer<ListsProvider>(
      builder: (context, lists, child) {
      lists.mainList = jsonList;
      return ListView.builder(
          itemCount: lists.mainList.length,
          itemBuilder: (context, index) {
            return Card(
              child: Text(lists.mainList[index].nome!),
            );
          });
    });
  }
}
0 Answers
Related