Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter - how to get current context?

I am using Firebase cloud messaging for notifications, and i want to show a dialog or snackbar once i receive a notification when i am inside the application, my problem is that i am initializing the firebase configuration at the top of my widget tree (Splash screen once the app is starting)

_fireBaseMessaging.configure(
  onMessage: (Map<String, dynamic> message) async {
    dynamic data = message['data'];
    ................ // Adding a snackbar/alertdialog here doesn't work
  },
);

obviously if i set a dialog or snackbar it won't show since i need the context of my current page, is there any way to get the current context?

I also tried putting it inside the build widget of my splash screen but still the dialog isn't showing once i am on another page.

 @override
  Widget build(BuildContext context) {
    _fireBaseMessaging.configure(
      onMessage: (Map<String, dynamic> message) async {
        print("onMessage: $message");
        dynamic data = message['data'];
        if (data['id'] == '1') {
          newPro = true;
        } else if (data['id'] == '2') {
          print("THIS WORKS!!!");
          showDialog(
              context: context,
              builder: (context) => AlertDialog(
                    content: ListTile(
                      title: Text("TEST"),
                      subtitle: Text("TEST"),
                    ),
                    actions: <Widget>[
                      FlatButton(
                        child: Text("OK"),
                        onPressed: () => Navigator.pop(context),
                      )
                    ],
                  ));
        }
      },
    );
like image 220
Bahij.Mik Avatar asked Jan 04 '20 20:01

Bahij.Mik


2 Answers

Because it makes me uncomfortable to have the answer embedded in a link, here is the answer (credit to xqwzts on Github).

Use a GlobalKey you can access from anywhere to navigate:

Create the key:

final GlobalKey<NavigatorState> navigatorKey = new GlobalKey<NavigatorState>();

Pass it to your App:

new MaterialApp(
      title: 'MyApp',
      onGenerateRoute: generateRoute,
      navigatorKey: navigatorKey,
    );

Push routes:

navigatorKey.currentState.pushNamed('/someRoute');
like image 103
Rob Caraway Avatar answered Oct 23 '22 00:10

Rob Caraway


I had the exact same issue, but I found a brilliant thread on GitHub. Basically, you can create a navigatorKey and pass that in to MaterialApp, and then use that navigatorKey to change route.

See how in this thread: https://github.com/brianegan/flutter_redux/issues/5#issuecomment-361215074

like image 25
Tommy Østgaard Avatar answered Oct 23 '22 01:10

Tommy Østgaard