【问题标题】:Flutter Riverpod: Refresh Page Offscreen using State NotifierFlutter Riverpod:使用状态通知器刷新屏幕外页面
【发布时间】:2021-05-25 10:00:10
【问题描述】:

我正在使用 StateNotifier 和 Riverpod。 我有一个通知页面,其中包含通知列表。当通知到达时,我会触发通知刷新。但是,当我导航到通知页面时,它仍然使用旧的(缓存?)列表。

如何在屏幕外刷新页面?

前台消息

FirebaseMessaging.onMessage.listen((RemoteMessage message) {
  _localNotification.showLocalNotification(message);
  ProviderContainer().read(notificationProvider).getNotification();
});

后台消息

Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  await Firebase.initializeApp();

  final LocalNotification localNotification = LocalNotification();
  await localNotification.init();
  localNotification.showLocalNotification(message);
  ProviderContainer().read(notificationProvider).getNotification();
}

通知提供者

Future<void> getNotification() async {
  try {
    state = const NotificationLoadingState();
    _notificationList = await _notificationRepository.getNotification();
    state = NotificationLoadedState(_notificationList); // ==> I get a new list here
  } catch (e, s) {
    state = const NotificationErrorState('error fetching notification');
  }
}

用户界面

final state = watch(notificationProvider.state);
if (state is NotificationLoadingState) {
  return _buildLoading();
} else if (state is NotificationLoadedState) {
  return _buildLoaded(state.notificationList); // ==> I still get the old list here
} else if (state is NotificationErrorState) {
  return _buildError(state.message);
}

编辑:

我设法通过使用navigatorKey.currentContext 解决了前台消息处理程序。

但是,我仍然没有解决后台消息处理程序。 我尝试将main.dart 更改为将UncontrolledProviderScope 与全局ProviderContainer 一起使用,然后从后台消息处理程序中调用它。还是不清爽。

【问题讨论】:

    标签: flutter refresh riverpod


    【解决方案1】:

    通过这一行,您正在为您的提供者创建一个新实例:

     ProviderContainer().read(notificationProvider).getNotification();
    

    您需要使用上下文来获取 ProviderContainer 的现有实例:

    context.read(notificationProvider).getNotification();
    

    或者如果您不在 ui 中,请在您的提供程序之间建立依赖关系

    【讨论】:

    • 你是对的。我设法使用navigatorKey.currentContext 刷新它。你有关于如何在提供者之间添加依赖关系的示例吗?你用ProviderReference吗?因为我在从 UI 外部调用它时仍然有点迷失。那我不使用ProviderContainer吗?
    • 我尝试将我的main.dart 更改为将UncontrolledProviderScope 与全局ProviderContainer 一起使用,这表示容器是我从后台消息处理程序中调用的容器。但是,它仍然不令人耳目一新。
    • 使用 ProviderReference 添加提供者之间的依赖关系。由于我不熟悉 firebase 和流,因此无法为您提供更多帮助。但是您应该为您的 Firebase 实例创建一个 Provider,为您的消息流创建一个 streamProvider,并通过调用 ref.watch(streamProvider) 使您的 notificationProvider 依赖于它。因此,每次您的流发出一个值时,您的通知提供程序都会用新值重新实例化
    猜你喜欢
    • 1970-01-01
    • 2021-04-30
    • 1970-01-01
    • 2022-09-27
    • 2021-08-06
    • 1970-01-01
    • 2021-02-10
    • 1970-01-01
    • 2021-11-29
    相关资源
    最近更新 更多