【发布时间】: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<TimersModel>(context)... 吗?
或者这是否可行,而我做错了什么?
【问题讨论】: