【发布时间】:2020-06-25 05:05:53
【问题描述】:
我必须在 AppBar 中的 IconButton 并且在新闻上我想使用 Providers 包更改字体大小。 但我不断收到此错误消息:
错误:在此上方找不到正确的提供程序 主页小部件
这可能是因为您使用了
BuildContext包括您选择的提供商。有几种常见的情况:
您尝试读取的提供程序位于不同的路径中。
提供者是“范围的”。因此,如果您在路线内插入提供者, 那么其他路由将无法访问该提供程序。
HomePage.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();
}
}
【问题讨论】: