Flutter : Provider error how to add new page

Issue

Sorry, this is my first time using a provider
I don’t know how to make the button take me to another page
I made a web page with filters
Main Screen

Scaffold(
  key: context.read<MenuController>().scaffoldKey,
  drawer: DrawerView(),
  body: Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [

        if (Responsive.isDesktop(context))
          Expanded(
            flex: 2,
            // default flex = 1
            // and it takes 1/6 part of the screen
            child: DrawerView(),
          ),
        // We want this side menu only for large screen

        Expanded(
          // It takes 5/6 part of the screen
          flex: 8,
          child: DashboardScreen(),
        ),
      ],
    ),
);

The page is divided into three parts
The provider part, the dashboard part, and the stats part

Menu Controller

    class MenuController extends ChangeNotifier {
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

  GlobalKey<ScaffoldState> get scaffoldKey => _scaffoldKey;

  void controlMenu() {
    if (!_scaffoldKey.currentState!.isDrawerOpen) {
      _scaffoldKey.currentState!.openDrawer();
    }
  }


}

main.dart

home: MultiProvider(
    providers: [
      ChangeNotifierProvider(
        create: (context) => MenuController(),
      ),
    ],
    child: MainScreen(),
  ),

Error: Could not find the correct Provider above this MainScreen 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.

Solution

Declare & implement provider like below

 @override
      Widget build(BuildContext context) {
        return MultiProvider(
          providers: [
            ChangeNotifierProvider(
              create: (context) => MenuController(),
            ),
          ],
          child: MainScreen(),
        );
      }

Answered By – Babul

Answer Checked By – Dawn Plyler (FlutterFixes Volunteer)

Leave a Reply

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