繁体   English   中英

如何在Flutter中的单例内部使用Provider.of(...)?

[英]How to use Provider.of(…) inside a singleton in Flutter?

我将这个widget放在小部件树的深处:

Widget build(BuildContext context) {
return ChangeNotifierProvider(
  builder: (context) => TimersModel(context: context),
  child: Scaffold(...

TimersModel获取上下文:

class TimersModel extends ChangeNotifier {
  final BuildContext context;
  NotificationsService _notificationsService;

  TimersModel({@required this.context}) {
    _notificationsService = NotificationsService(context: context);
  }

并首次实例化此NotificationsService单例:

class NotificationsService {
  static FlutterLocalNotificationsPlugin _flutterLocalNotificationsPlugin;

  final BuildContext context;

  static NotificationsService _instance;

  factory NotificationsService({@required BuildContext context}) {
    _instance ??= NotificationsService._internalConstructor(context: context);
    return _instance;
  }

  NotificationsService._internalConstructor({@required this.context}) {

如您所见,这是FlutterLocalNotificationsPlugin的单例

问题是,如果我从此单例调用Provider.of<TimersModel>(context)... ,尽管它获取正确的上下文,但它始终会抛出ProviderNotFoundError

如果我在提供程序的此代码上放置了一个断点:

static T of<T>(BuildContext context, {bool listen = true}) {
    // this is required to get generic Type
    final type = _typeOf<InheritedProvider<T>>();
    final provider = listen
        ? context.inheritFromWidgetOfExactType(type) as InheritedProvider<T>
        : context.ancestorInheritedElementForWidgetOfExactType(type)?.widget
            as InheritedProvider<T>;

    if (provider == null) {
      throw ProviderNotFoundError(T, context.widget.runtimeType);
    }

    return provider._value;
  }

上下文ChangeNotifierProvider和类型TimersModel是正确的。 但是provider始终为null。

我知道单例不是小部件,当然,它不在小部件树中。

但是,只要提供正确的上下文和类型,我是否应该可以从任何地方调用Provider.of<TimersModel>(context)...

还是应该这样做,而我做错了什么?

由于Provider按类型进行查找,因此在构建方法中返回ChangeNotifierProvider时,请尝试为其提供一种类型:

return ChangeNotifierProvider<TimersModel>(...);

我可以想象Provider根本找不到TimersModel的实例,因为您没有声明该类型的提供者。

暂无
暂无

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

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