【问题标题】:Flutter: access provider from outside the widget treeFlutter:从小部件树外部访问提供者
【发布时间】:2021-02-20 19:18:04
【问题描述】:

在我的 Flutter 应用程序中,我必须在推送通知到达后立即更新 Provider 的状态保持,以便可以重建 UI。 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

    });
  }
}

这是我的简单提供者:

class NewsProvider with ChangeNotifier {
  List<News> _news;
  get news => _news;

  NewsProvider();

  void addNews(News news) {
    _news.add(news);
    notifyListeners();
  }
}

由于 PushNotifications 类没有上下文,我无法想出如何实现这一点。

【问题讨论】:

标签: flutter push-notification provider flutter-state


【解决方案1】:

请查看 Riverpod,它基本上是无限制的提供者。 Riverpod 与 Provider 非常相似,也是由同一作者 Remi Rousselet 创建的。

根据作者:

Riverpod 项目可以被视为对提供者的重写,以进行原本不可能的改进。

Riverpod官网:https://riverpod.dev/

Pub.dev 上的 Riverpod:https://pub.dev/packages/riverpod

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-21
    • 2021-11-13
    • 2020-06-08
    • 2021-08-12
    • 2020-09-10
    • 1970-01-01
    • 2020-03-22
    • 2018-07-01
    相关资源
    最近更新 更多