簡體   English   中英

Flutter Riverpod:使用 State 通知程序在屏幕外刷新頁面

[英]Flutter Riverpod: Refresh Page Offscreen using State Notifier

我正在使用 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 內部,請在您的提供程序之間建立依賴關系

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM