flutter - 无法在颤振中访问提供者
问题描述
我有一个简单的提供者类:-
class DataProvider with ChangeNotifier {
int count;
void updateCount() {
count = count + 1;
notifyListeners();
}
}
我将此提供程序附加到以下类:-
class MyWidget extends StatelessWidget{
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (context) => DataProvider(),
child: Scaffold(
body: raisedButton(
onPressed: () {
Provider.of<DataProvider>(context).updateCount();
}
child: Text("Click!")
),
),
),
}
及其给我以下错误:-
I/flutter (32011): Error: Could not find the correct Provider<DataProvider> above this MyWidget
Widget
I/flutter (32011): To fix, please:
I/flutter (32011): * Ensure the Provider<DataProvider> is an ancestor to this MyWidget Widget
I/flutter (32011): * Provide types to Provider<DataProvider>
I/flutter (32011): * Provide types to Consumer<DataProvider>
I/flutter (32011): * Provide types to Provider.of<DataProvider>()
I/flutter (32011): * Ensure the correct `context` is being used.
这可能是什么原因?
编辑:-
当我从我定义的小部件的任何子小部件访问提供程序时,它工作正常。ChangeNotifierProvider
.
解决方案
你需要把你raisedButton
的Consumer
.
Consumer 小部件有两个主要用途:
当我们没有作为所述提供者的后代的 BuildContext 时,它允许从提供者获取值,因此不能使用 Provider.of。当创建提供者的小部件也是其消费者之一时,通常会发生这种情况,如下例所示:
@override Widget build(BuildContext context) { return ChangeNotifierProvider( create: (_) => Foo(), child: Text(Provider.of<Foo>(context).value), ); }
此示例将引发 ProviderNotFoundException,因为 Provider.of 是使用作为提供程序的祖先的 BuildContext 调用的。
相反,我们可以使用 Consumer 小部件,它将使用自己的 BuildContext 调用 Provider.of。
使用 Consumer,前面的例子会变成:
@override Widget build(BuildContext context) { return ChangeNotifierProvider( create: (_) => Foo(), child: Consumer<Foo>( builder: (_, foo, __) => Text(foo.value), }, ); }
这不会抛出 ProviderNotFoundException 并且会正确构建文本。每当值 foo 更改时,它也会更新 Text。
请参阅:https ://pub.dev/documentation/provider/latest/provider/Consumer-class.html
推荐阅读
- sql - Knex.js PostgreSQL 列引用“created_at”不明确
- python - 您如何找到在每个月底重新开始的值的滚动最大值?熊猫蟒
- neo4j - 即使在安装插件后,Nepo4j 也无法使用 apoc 功能
- java - Java Iterator 正在跳过一半元素
- javascript - Angular 中的 Counter Up v2 插件(动画计数器)
- oracle - Oracle 访问 SQL 中的可变数组元素
- android - 使用 OR 运算符进行条件渲染
- azure - 可以使用 Powershell 导出 Azure 中的资源配置吗?
- prestashop - 将 prestashop 从 1.7.5 更新到 1.7.7.2 后出错
- next.js - 使用 res.writeHead() 将标头发送到客户端后无法设置标头