我在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)...
但是,只要我提供正确的上下文和类型,我就不能从任何地方调用吗?
或者这应该起作用而我做错了什么?