I have a contacts application in Flutter. I call a function in my ContactListPage statefull class using GlobalKey in another class called PushMessageManager. When I delete the application and run it for the first time and a notification comes to the application, I get the error "The method 'refreshContactsFromServer' was called on null". However, when I close the application and open it again, the function works as I want.
I wonder what I'm missing? Any ideas on how I can solve this? My codes are as follows:
final contactListPageKey = GlobalKey<ContactListPageState>();
routes: <String, WidgetBuilder>{
'/login': (BuildContext context) => LoginScene(),
'/contactList': (context) => ContactListPage(key: contactListPageKey),
'/contact': (context) => ContactPage(),
},
FirebaseMessaging.onMessage.listen((RemoteMessage remoteMessage) async {
if (remoteMessage.data.isNotEmpty) {
if (remoteMessage.data["type"] == "message") {
await contactListPageKey.currentState.refreshContactsFromServer();
print("Contacts are updated.");
}
}
I tried methods such as FutureDelayed and await but nothing changes.
Future.delayed(const Duration(seconds: 1), () {
contactListPageKey.currentState.refreshContactsFromServer();
});