flutter - 如何在 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)...
但是,只要我提供正确的上下文和类型,我就不能从任何地方调用吗?
或者这应该起作用而我做错了什么?
解决方案
由于 Provider 按类型进行查找,当您在构建方法中返回它时,请尝试为您的 ChangeNotifierProvider 提供一个类型:
return ChangeNotifierProvider<TimersModel>(...);
我可以想象 Provider 根本找不到 TimersModel 的实例,因为您没有声明该类型的提供者。
推荐阅读
- javascript - 在坐标数组中找到最接近给定的点
- php - 如何为自联接设置 Eloquent 模型 ManyToMany
- html - 红框未按预期放置
- java - 如何在单个数据库调用中进行删除和选择?
- java - Android RecyclerView 阻止回收所有项目
- javascript - 字符串比较 Javascript
- botframework - Azure 机器人通道注册中 Okta 的通用 OAuth 提供程序
- php - 比较 2 个 MYSQL 表以查找匹配数据 PHP
- javascript - Gatsby 中库的条件导入
- java - JAVA List GroupBy 多个字段和 Sum