问题描述
我正在尝试在Flutter应用中实施一些基本的状态管理.在小部件树的某个位置,我有一个供用户使用的提供程序.进一步向下的小部件可以使用使用者用户小部件"访问用户.但是,使用Navigator.push()构建了一个小部件(下面代码中的WidgetB),无法访问用户.按下按钮将引发错误:
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:
floatingActionButton: FloatingActionButton(
child: Icon(Icons.play),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Consumer<User>(
builder: (context, user, child) => WidgetB(user: user),
),
),
);
},
),
如何在WidgetB(或WidgetB的某些子Widget)中访问用户?
How can I access the user in WidgetB (or in some child Widget of WidgetB)?
推荐答案
确保您的提供者设置在MaterialApp级别.例如,像这样:
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(),
);
}
}
这篇关于Navigator.push():错误:在此消费者小组件上方找不到正确的提供者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!