[英]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.