[英]Flutter: access provider from outside the widget tree
In my Flutter app I have to update the state hold by a Provider as soon as a push notification arrives so that the UI can be rebuilt.在我的 Flutter 应用程序中,我必须在推送通知到达时立即更新 Provider 保持的状态,以便可以重建 UI。 The PushNotifications service is a class (not a widget) like that: PushNotifications 服务是一个类(不是小部件),如下所示:
class PushNotifications {
...
Future<void> init() async {
_firebaseMessaging.configure(onMessage: (Map<String, dynamic> data) {
// here I receive the data from the notification that I have to add to the provider
});
}
}
And this is my simple provider:这是我的简单提供者:
class NewsProvider with ChangeNotifier {
List<News> _news;
get news => _news;
NewsProvider();
void addNews(News news) {
_news.add(news);
notifyListeners();
}
}
I can't come up with how I can achive that since the PushNotifications class doesn't have a context.由于 PushNotifications 类没有上下文,我无法想出如何实现这一点。
Please check out Riverpod which is basically Provider without its limitation.请查看 Riverpod,它基本上是 Provider,没有它的限制。 Riverpod is very similar to Provider and also created by the same author Remi Rousselet. Riverpod 与 Provider 非常相似,也是由同一作者 Remi Rousselet 创建的。
According to the author :根据作者的说法:
Riverpod project can be considered as a rewrite of provider to make improvements that would be otherwise impossible. Riverpod项目可以被视为对供应商的重写,以进行原本不可能进行的改进。
Official website of Riverpod : https://riverpod.dev/ Riverpod官方网站: https ://riverpod.dev/
Riverpod on Pub.dev : https://pub.dev/packages/riverpod Pub.dev 上的 Riverpod: https ://pub.dev/packages/riverpod
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.