I want to call the function we defined in a stateful widget class when a notification comes to the phone, so I need to use it in another class.
For example:
class ContactListPage extends StatefulWidget {
@override
_ContactListPageState createState() => _ContactListPageState();
}
class _ContactListPageState extends State<ContactListPage>{
doSomething(){
print("do something");
}
}
-------------------------------------------------- ----------------------------------------
class PushMessageManager {
configureNotificationsActions() async {
FirebaseMessaging.onMessage.listen((RemoteMessage remoteMessage) {
if (remoteMessage.data.isNotEmpty) {
if (remoteMessage.data["type"] == "message") {
// ContactListPage.doSomething();
}
}
}
}
I tried calling directly, but I couldn’t get what I wanted. What method should I use? Thank you for your help.
2
Answers
I will suggest you to use event_bus to achieve what you want.
demo code:
The
_ContactListPageState
is private (as indicated by the_
, so you won’t be able to see the function.If you want to call a method in the state of a
StatefulWidget
, you can use aGlobalKey
, like in this other answer: https://stackoverflow.com/a/46545141/15469537Steps:
_ContactListPageState
public (refactor it to remove the_
)_
)GlobalKey
in a main/parent Widget (which you can use in your message handler)Note that if the Widget is not mounted, this will not call the function at all, so make sure to think about the different possible states of the app when the message is received.
Recommendation
It’s recommended to have a global/static function to handle notifications which can, for instance, store something in the
SharedPreferences
so that the rest of the app has access to it when needed.