Navigator.push(): Error: Could not find the correct Provider above this Consumer Widget

梦想的初衷 提交于 2020-03-04 05:07:06

问题


Im trying to implement some basic state management in my Flutter app. Somewhere up the Widget tree I have a Provider for a User. Widgets further down can access the User using the Consumer User Widget. However one Widget (WidgetB in the code snipped below) is build using the Navigator.push() and cant access the User. Pushing the Button will throw the Error:

Error: Could not find the correct Provider above this Consumer Widget

floatingActionButton: FloatingActionButton(
          child: Icon(Icons.play),
          onPressed: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => Consumer<User>(
                  builder: (context, user, child) => WidgetB(user: user),
                ),
              ),
            );
          },
        ),

How can I access the user in WidgetB (or in some child Widget of WidgetB)?


回答1:


Make sure that your providers are set at the MaterialApp level. For example, like this:

void main() {
  runApp(MultiProvider(
    providers: [
      ChangeNotifierProvider(
        create: (_) => Provider1(),
      ),
      ChangeNotifierProvider(
        create: (_) => Provider2(),
      ),
    ],
    child: MyApp(),
  ));
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MainPage(),
    );
  }
}


来源:https://stackoverflow.com/questions/60045822/navigator-push-error-could-not-find-the-correct-provider-above-this-consumer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!