我无法从 FloatingActionButton 中的 showModalBottomSheet 访问在 Scaffold 上方定义的提供程序。
我已经像这样定义了一个主页:
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (_) => MyProvider(),
builder: (context, _) {
return Scaffold(
body: Consumer<MyProvider>(
builder: (context, provider, _) {
return Text(provider.mytext); // this works fine
}
),
floatingActionButton: MyFAB(), // here is the problem
);
}
)
}
}
这是 MyFAB:
class MyFAB extends StatefulWidget {
@override
_MyFABState createState() => _MyFABState();
}
class _MyFABState extends State<MyFAB> {
@override
Widget build(BuildContext context) {
return FloatingActionButton(
...
onPressed: () => show(),
);
}
void show() {
showModalBottomSheet(
...
context: context,
builder: (BuildContext context) {
return Wrap(
children: [
...
FlatButton(
onPressed: Provider.of<MyProvider>(context, listen: false).doSomething(); //Can't do this
Navigator.pop(context);
)
],
);
}
);
}
}
错误:在此 BottomSheet 小部件上方找不到正确的 Provider<MyProvider。