flutter: You used a `BuildContext` that is an ancestor of the provider you are trying to read
程序员文章站
2022-06-16 13:42:33
...
当在StatefulWidget中使用ChangeNotifierProvider绑定ViewModel,就会报如上错误,完整的错误日志如下
Error: Could not find the correct Provider<RecordTopViewModel> above this RecordTop Widget
This likely happens because you used a `BuildContext` that does not include the provider
of your choice. There are a few common scenarios:
- The provider you are trying to read is in a different route.
Providers are "scoped". So if you insert of provider inside a route, then
other routes will not be able to access that provider.
- You used a `BuildContext` that is an ancestor of the provider you are trying to read.
Make sure that RecordTop is under your MultiProvider/Provider<RecordTopViewModel>.
This usually happen when you are creating a provider and trying to read it immediately.
For example, instead of:
```
Widget build(BuildContext context) {
return Provider<Example>(
create: (_) => Example(),
// Will throw a ProviderNotFoundError, because `context` is associated
// to the widget that is the parent of `Provider<Example>`
child: Text(context.watch<Example>()),
),
}
```
consider using `builder` like so:
```
Widget build(BuildContext context) {
return Provider<Example>(
create: (_) => Example(),
// we use `builder` to obtain a new `BuildContext` that has access to the provider
builder: (context) {
// No longer throws
return Text(context.watch<Example>()),
}
),
}
```
If none of these solutions work, consider asking for help on *:
https://*.com/questions/tagged/flutter
解决方案:在布局最外层,用Consumer<ViewModel>(builder:XXX)包裹上:
child: Consumer<RecordTopViewModel>(builder: (context, value, child) {
return Scaffold(
)