首页 > 解决方案 > 如何在 Flutter 的单例中使用 Provider.of(...)?

问题描述

我在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.of<TimersModel>(context)...但是,只要我提供正确的上下文和类型,我就不能从任何地方调用吗?

或者这应该起作用而我做错了什么?

标签: flutterflutter-provider

解决方案


由于 Provider 按类型进行查找,当您在构建方法中返回它时,请尝试为您的 ChangeNotifierProvider 提供一个类型:

return ChangeNotifierProvider<TimersModel>(...);

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


推荐阅读