final alertsScreen = AlertsScreen(userId: loginController.currentUser.value?.id ?? '');
Navigator.push(context, MaterialPageRoute(builder: (context) => alertsScreen));
Future<bool> _onWillPop() async {
// Reload data when the user presses the back button
await fetchNotifications;
await markNotificationAsRead;
await _showNotificationDetails;
print("hello");
Navigator.pop(context, alerts.length);
return true;
// Allow the back navigation
}
i use this fuction in back screen go but not page refresh and not update notificatoion count
3
Answers
The problem is that you are using
Navigator.pop()
to return to the previous page. This will simply pop the previous page off the navigation stack, without reloading it.To reload the previous page, you can use
Navigator.pushReplacement()
instead. This will push a new instance of the previous page onto the navigation stack, effectively replacing the existing instance.If you insist on using Navigator.pop(), you have to consider using state management. State management will take care of the rebuilding of widgets that watches any changes in an object (in your case, an int notificationCount), reflecting the most updated value of the object.
Additional Note:
There are many reliable state management packages on offer in pub.dev. You can choose one that you are most comfortable with. I personally use riverpod.
An example for your case using riverpod.
Add the Riverpod package to your pubspec.yaml file.
Create a file, e.g. lib/tool/provider/notificationCount.dart and create notifier provider for the object you want to keep track of, in this case is the notificationCount int.
Since it is a simple integer type object, using State Provider should be ample.
to update the value on following an event (for example a button click), you can use ConsumerWidget as follow,
Then in your second screen, where you put the event logic that changes the notification count,
When SecondScreen pop to FirstScreen, the notificationCount, will reflect the latest value.
Using state management is highly recommended as it will make your code more robust, and easier to maintain as your code base grows.
Here’s a very good resource to learn about riverpod.