Error: Could not find the correct Provider<UsersProvider> above this AdminDashboardPage Widget

Issue

  • This is my admin_dashboardpage.dart
  • I am clicking on a button and then this page is opening up
  • I am making this app where I am retrieving the data from the firestore. I am unable to get through it as soon as I am clicking on the admindashboard I am getting the error mentioned after the code.
import 'package:flutterapp/admin_ui/user_disable_page.dart';
import 'package:flutterapp/admin_ui/user_enable_page.dart';

import 'package:flutterapp/admin_ui/shadow_container.dart';
import 'package:flutterapp/admin_ui/admin_user.dart';
import 'package:flutterapp/providers/users_provider.dart';

import 'package:flutter/material.dart';
import 'package:flutterapp/database/Admin.dart';
import 'package:provider/provider.dart';

import 'package:flutterapp/admin_ui/page_header.dart';

class AdminDashboardPage extends StatefulWidget {
  AdminDashboardPage({Key key}) : super(key: key);

  @override
  _AdminDashboardPageState createState() => _AdminDashboardPageState();
}

class _AdminDashboardPageState extends State<AdminDashboardPage> {
  @override
  Widget build(BuildContext context) {
    final usersProvider = Provider.of<UsersProvider>(context);
    return Scaffold(
      body: ListView(
        children: <Widget>[
          PageHeader(
            title: 'Users Dashboard',
          ),
          for (int i = 0; i < usersProvider.users.length; i++)
            AdminUserItem(
              adminuser: usersProvider.users[i],
            ),
        ],
      ),
      floatingActionButton: Container(
        margin: EdgeInsets.only(bottom: 10),
        child: FloatingActionButton.extended(
            onPressed: () {
              Navigator.of(context).push(
                new MaterialPageRoute<Null>(
                    builder: (BuildContext context) {
                      return Admin();
                    },
                    fullscreenDialog: true),
              );
            },
            icon: Icon(
              Icons.add,
            ),
            label: Text("Create Admin")),
      ),
    );
  }
}

class AdminUserItem extends StatelessWidget {
  final AdminUser adminuser;
  const AdminUserItem({
    this.adminuser,
    Key key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ShadowContainer(
      child: Column(
        children: <Widget>[
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Text(adminuser.name),
                  SizedBox(height: 3),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      Text(adminuser.email),
                    ],
                  ),
                ],
              ),
              Column(
                children: <Widget>[
                  SizedBox(height: 8),
                  InkWell(
                    onTap: () {
                      Navigator.of(context).push(
                        new MaterialPageRoute<Null>(
                            builder: (BuildContext context) {
                              return UserDisablePage(
                                user: adminuser,
                              );
                            },
                            fullscreenDialog: true),
                      );
                    },
                    child: Container(
                      padding: EdgeInsets.symmetric(horizontal: 10, vertical: 6),
                      decoration:
                      BoxDecoration(border: Border.all(color: Theme.of(context).buttonColor), borderRadius: BorderRadius.circular(20)),
                      child: Text(
                        'Disable Account',
                        style: TextStyle(fontSize: 12, color: Theme.of(context).buttonColor),
                      ),
                    ),
                  ),
                  SizedBox(height: 8),
                  InkWell(
                    onTap: () {
                      Navigator.of(context).push(
                        new MaterialPageRoute<Null>(
                            builder: (BuildContext context) {
                              return UserEnablePage(
                                user: adminuser,
                              );
                            },
                            fullscreenDialog: true),
                      );
                    },
                    child: Container(
                      padding: EdgeInsets.symmetric(horizontal: 10, vertical: 6),
                      decoration:
                      BoxDecoration(border: Border.all(color: Theme.of(context).buttonColor), borderRadius: BorderRadius.circular(20)),
                      child: Text(
                        'Enable Account',
                        style: TextStyle(fontSize: 12, color: Theme.of(context).buttonColor),
                      ),
                    ),
                  ),
                ],
              ),
            ],
          ),
        ],
      ),
    );
  }
}
  • Another file named as users_provider.dart
import 'package:flutter/material.dart';

import 'package:flutterapp/admin_ui/admin_user.dart';
import 'package:flutterapp/services/users_services.dart';

class UsersProvider with ChangeNotifier {
  bool _isLoading = false;
  bool get isLoading => _isLoading;

/* ------------------------------- NOTE Users ------------------------------- */
  List<AdminUser> _users = [];
  List<AdminUser> get users => _users;

  Future initState() async {
    var res = await UsersService.streamUsers();
    res.listen((r) {
      _users = r;
      notifyListeners();
    });
  }

  Future disableUser({AdminUser user}) async {
    await UsersService.disableUser(user: user);
  }

  Future enableUser({AdminUser user}) async {
    await UsersService.enableUser(user: user);
  }
}
  • Error I am facing
════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
The following ProviderNotFoundError was thrown building AdminDashboardPage(dirty, state: _AdminDashboardPageState#713d8):
Error: Could not find the correct Provider<UsersProvider> above this AdminDashboardPage Widget

To fix, please:

  * Ensure the Provider<UsersProvider> is an ancestor to this AdminDashboardPage Widget
  * Provide types to Provider<UsersProvider>
  * Provide types to Consumer<UsersProvider>
  * Provide types to Provider.of<UsersProvider>()
  * Always use package imports. Ex: `import 'package:my_app/my_code.dart';
  * Ensure the correct `context` is being used.

If none of these solutions work, please file a bug at:
https://github.com/rrousselGit/provider/issues

The relevant error-causing widget was: 
  AdminDashboardPage file:///home/cerelabs/AndroidStudioProjects/flutterapp/flutterapp/lib/ui/home.dart:50:70
When the exception was thrown, this was the stack: 
#0      Provider.of (package:provider/src/provider.dart:264:7)
#1      _AdminDashboardPageState.build (package:flutterapp/admin_ui/admin_dashboardpage.dart:24:36)
#2      StatefulElement.build (package:flutter/src/widgets/framework.dart:4619:28)
#3      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4502:15)
#4      StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4675:11)
...
════════════════════════════════════════════════════════════════════════════════════════════════════

— This is the structure of the files
enter image description here

Solution

You need to register the Provider first. This can be done anywhere above(in the Widget tree) where you want to use the Provider.

If your Provider is required pretty much everywhere in the App for instance, it is a good idea to register it in your main.dart file.
If you want to register multiple Providers, you can use MultiProvider

Snippet from my main.dart file:

    class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(
          builder: (_) => Galleries(),
        ),
        ChangeNotifierProvider(
          builder: (_) => Fotos(),
        ),
      ],
      child: MaterialApp(

Answered By – Benedikt J Schlegel

Answer Checked By – Terry (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *