Flutter Riverpod:使用状态通知程序在屏幕外刷新页面 前台消息背景信息通知提供者界面

问题描述

我正在使用 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 一起使用,然后从后台消息处理程序调用它。它仍然没有令人耳目一新。

解决方法

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

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

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

context.read(notificationProvider).getNotification();

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