flutter - 找不到正确的提供者在此主页小部件上方
问题描述
我必须在AppBar中使用IconButton ,并且在按下时我想使用Providers Package 更改字体大小。但我不断收到此错误消息:
错误:在此主页小部件上方找不到正确的提供程序
这可能是因为您使用了
BuildContext
不包括您选择的提供者的 a。有几种常见的场景:
您尝试读取的提供程序位于不同的路径中。
提供者是“范围的”。因此,如果您在路由中插入提供程序,那么其他路由将无法访问该提供程序。
主页.dart
class _HomePageState extends State<HomePage> {
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider<FontSizeHandler>(
create: (BuildContext context) => FontSizeHandler(),
child: Scaffold(
appBar: AppBar(
actions: <Widget>[
IconButton(
icon: Icon(Icons.arrow_upward),
onPressed: () {
Provider.of<FontSizeHandler>(context, listen: false)
.increaseFont();
},
),
],
),
body: Consumer<FontSizeHandler>(builder: (context, myFontHandler, _) {
return Container(
child: AutoSizeText(
kDummy,
style: TextStyle(fontSize: myFontHanlder.fontSize),
),
);
}),
),
);
}
}
FontChangeHandler.dart
class FontSizeHandler extends ChangeNotifier {
double fontSize = 15;
void increaseFont() {
fontSize = fontSize + 2;
notifyListeners();
}
void decreaseFont() {
fontSize = fontSize - 2;
notifyListeners();
}
}
解决方案
问题是您正试图访问您在同一build
方法上创建的信息。
在您“使用”提供者之前,您需要构建一个小部件以确保您的提供者的创建发生。
如果您不想创建新的 StateLess/StateFull 小部件,请添加这样的Builder:
...body: Builder(
builder:(BuildContext context)=> Consumer<FontSizeHandler>(...))
这样,Builder将确保您的父提供者在使用它之前得到构建。
编辑:
如果您希望 Provider 在同一个 Stateful/Stateless Widget 中成为 Consumable,那么上面的答案就可以了。
如果您需要从 Flutter App 中的任何位置访问 Provider,请确保在 MaterialApp/CupertinoApp 之前创建 Provider。