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

yno*_*tu. 4 flutter flutter-state

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),
                ),
              ),
            );
          },
        ),
Run Code Online (Sandbox Code Playgroud)

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

msk*_*ick 6

确保您的提供程序设置在 MaterialApp 级别。例如,像这样:

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(),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)