私は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
は正しいです。ただし、プロバイダーは常に null です。
シングルトンはウィジェットではなく、もちろんウィジェット ツリーにもありません。
Provider.of<TimersModel>(context)...
しかし、適切なコンテキストとタイプを提供する限り、どこからでも呼び出すことができるべきではないでしょうか?
それとも、これはうまくいくはずで、私は何か間違ったことをしていますか?