首页 > 解决方案 > 无法在颤振中访问提供者

问题描述

我有一个简单的提供者类:-

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.

标签: flutterprovider

解决方案


你需要把你raisedButtonConsumer.

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


推荐阅读