简体   繁体   English

如何在 Flutter/Dart 中使用带有基类的 Provider

[英]How to use Provider with Base Class in Flutter/Dart

I have base and derived classes like this:我有这样的基类和派生类:

abstract class A extends ChangeNotifier{....}
class B extends A{....}

I am using provider like this:我正在使用这样的提供者:

ChangeNotifierProvider<B>(create: (context) => B())

and accessing using both A and B(depending on situation) like this:并使用 A 和 B(视情况而定)访问,如下所示:

Provider.of<A>(context) //This does not work. Why?
Provider.of<B>(context) //This works.

How do I correctly use base class with Provider.of ie Provider.of<A>(context) ?如何正确使用Provider.of基类,即Provider.of<A>(context)

Edit: The ChangeNotifierProvider is only for B. I do not have a provider for A. But, I want to access using A as A is the base class of B.编辑:ChangeNotifierProvider 仅适用于 B。我没有 A 的提供者。但是,我想使用 A 进行访问,因为 A 是 B 的基类。

You'll have to do something like this:你必须做这样的事情:

final b = B();
ChangeNotifierProvider<A>.value(value: b)
ChangeNotifierProvider<B>.value(value: b)

Then you can access your B class by using either:然后您可以使用以下任一方法访问您的B类:

Provider.of<A>(context) //This now works.
Provider.of<B>(context) //This works.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM