【问题标题】:How to use Provider.of(...) inside a singleton in Flutter?如何在 Flutter 的单例中使用 Provider.of(...)?
【发布时间】:2019-09-04 01:40:35
【问题描述】:

我的小部件树深处有这个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

如果我在 Provider 的这段代码上设置断点:

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&lt;TimersModel&gt;(context)... 吗?

或者这是否可行,而我做错了什么?

【问题讨论】:

    标签: flutter flutter-provider


    【解决方案1】:

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

    return ChangeNotifierProvider<TimersModel>(...);
    

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

    【讨论】:

    • 这应该不是问题,因为它在其他任何地方都有效。另外,据我所知 ChangeNotifierProvider 类型是在 builder 方法上设置的。另外,在调试的时候,类型是正确的。
    • 你找到解决办法了吗?
    猜你喜欢
    • 2020-03-05
    • 2020-11-17
    • 2020-12-10
    • 2020-07-27
    • 2021-02-21
    • 1970-01-01
    • 2020-07-16
    • 2021-04-29
    • 2020-10-16
    相关资源
    最近更新 更多