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

Flutter 如何在Flatter中的单例中使用(…)的Provider.of?,flutter,flutter-provider,Flutter,Flutter Provider,我在小部件树的深处有一个小部件: Widget build(BuildContext context) { return ChangeNotifierProvider( builder: (context) => TimersModel(context: context), child: Scaffold(... TimersModel获取上下文: class TimersModel extends ChangeNotifier { final BuildContext co

我在小部件树的深处有一个
小部件

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);
  }
并第一次也是唯一一次实例化此
通知服务
单例:

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}) {
如您所见,这是
flatterLocalNotificationsPlugin

问题是,如果我从这个单例调用
Provider.of(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;
  }
static T of(BuildContext上下文,{bool listen=true}){
//这是获取泛型类型所必需的
最终类型=_typeOf();
最终提供者=侦听
?context.inheritFromWidgetOfExactType(类型)作为InheritedProvider
:context.ancestorInheriteElementForWidgeToFexactType(类型)?.widget
作为继承提供者;
if(提供程序==null){
抛出ProviderNotFoundError(T,context.widget.runtimeType);
}
返回提供程序。\u值;
}
上下文
ChangeNotifierProvider
和类型
TimerModel
是正确的。但是提供者总是空的

我知道singleton不是一个小部件,当然,它不在小部件树中

但是,只要我提供了正确的上下文和类型,我就不能从任何地方调用(上下文)的提供者吗


或者这样做是否有效,而我做错了什么?

当提供程序按类型进行查找时,请尝试在生成方法中返回ChangeNotifierProvider类型时为其提供一个类型:

return ChangeNotifierProvider<TimersModel>(...);
返回ChangeNotifierProvider(…);

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

当提供程序按类型进行查找时,请尝试在生成方法中返回ChangeNotifierProvider时为其提供一个类型:

return ChangeNotifierProvider<TimersModel>(...);
返回ChangeNotifierProvider(…);

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

这不应该是问题,因为它在其他任何地方都可以工作。另外,据我所知,ChangeNotifierProvider类型是在builder方法上设置的。此外,在调试时,类型是正确的。您找到了解决方案吗?这不应该是问题,因为它在其他任何地方都可以工作。另外,据我所知,ChangeNotifierProvider类型是在builder方法上设置的。此外,在调试时,类型是正确的。您找到了解决方案吗?