53

I want to show an AlertDialog when a http get fails. The function showDialog (https://api.flutter.dev/flutter/material/showDialog.html) has the parameter "@required BuildContext context", but I want to call the AlertDialog from my async function getNews(), which hasn't a context value.

By analogy with Java, where I use null for dialog without an owner, I tried to put context value to null, but it is not accepted.

This is my code:

  Future<dynamic> getNews() async {
    dynamic retVal;
    try {
      var response = await http.get(url));
      if (response.statusCode == HttpStatus.ok) {
        retVal = jsonDecode(response.body);
      }
    } catch (e) {
      alertDlg(?????????, 'Error', e.toString());
  }
    return
    retVal;
  }

  static Future<void> alertDlg(context, String titolo, String messaggio) async {
    return showDialog<void>(
        context: context,
        barrierDismissible: false, // user must tap button!
        builder: (BuildContext context) {
        return AlertDialog(
              title: Text(titolo),
        ...
    );
  }
Francesco Pagano
  • 533
  • 1
  • 4
  • 5
  • Pass your `Build` context from `StatefulWidget` where you'll display the http response to your `getNews()` function . – Mazin Ibrahim May 23 '19 at 18:12
  • can you give an example please. I tried passing context to my new widget. It doesnt give any error but also doesnt show any alert – Aseem Jan 16 '20 at 03:53
  • bypassing null not getting any compile time error but getting same Failed assertion: line 'context != null': is not true. – s.j Oct 05 '20 at 10:19

6 Answers6

113

Solution without third-party libraries or storing BuildContext:

final navigatorKey = GlobalKey<NavigatorState>();

void main() => runApp(
  MaterialApp(
    home: HomePage(),
    navigatorKey: navigatorKey, // Setting a global key for navigator
  ),
);

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: SafeArea(
        child: Center(
          child: Text('test')
        )
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: showMyDialog, // Calling the function without providing it BuildContext
      ),
    );
  }
}

void showMyDialog() {
  showDialog(
    context: navigatorKey.currentContext,
    builder: (context) => Center(
      child: Material(
        color: Colors.transparent,
        child: Text('Hello'),
      ),
    )
  );
}

After setting a global key for navigator (navigatorKey parameter of MaterialApp class), its current state becomes accessible from any part of the code. We can pass its context to the showDialog function. Make sure not to use it before the first frame is built, otherwise the state will be null.

Basically, dialogs are just another type of routes like MaterialPageRoute or CupertinoPageRoute - they are all derived from the ModalRoute class and their instances are pushed into NavigatorState. Context is only needed to get the current navigator's state. A new route can be pushed without having a context if we have a global navigator key:

navigatorKey.currentState.push(route)

Unfortunately, _DialogRoute class (...\flutter\lib\src\widgets\routes.dart) used in showDialog function is private and unaccessible, but you make your own dialog route class and push it into the navigator's stack.

UPDATE: Navigator.of method has been updated and it's no longer needed to pass subtree context.

Igor Kharakhordin
  • 9,185
  • 3
  • 40
  • 39
  • Great hack! The `.overlay` saved my day! (I found that if directly use `navigatorKey.currentState.context`, it will not work because the showDialog needs a context *below* the Navigator context.) – ch271828n Jul 29 '20 at 08:51
  • 1
    How about using `navigatorKey.currentContext`? It seems to work, but I'm not sure if there are potential problems compared to `currentState.overlay.context`? – Magnus Sep 09 '20 at 06:54
  • Unhandled Exception: NoSuchMethodError: The getter 'overlay' was called on null. E/flutter (30999): Receiver: null E/flutter (30999): Tried calling: overlay – s.j Oct 06 '20 at 07:08
  • Unhandled Exception: NoSuchMethodError: The getter 'overlay' was called on null. getting error – s.j Oct 07 '20 at 06:51
  • @MagnusW You're right, navigator state's context can now be passed, because `Navigator.of` method got updated. – Igor Kharakhordin Oct 07 '20 at 08:18
  • @s.j Navigator's state is null. As I mentioned, do not access it before the first frame of the app is built (you're probably trying to do it in initState. You can use `addPostFrameCallback`). – Igor Kharakhordin Oct 07 '20 at 08:21
  • @IgorKharakhordin no, I trying to show a dialog in the API success method in but getting error of context, I follow the void showMyDialog() method but still getting context error. – s.j Oct 07 '20 at 09:20
  • @s.j have you set `navigatorKey` parameter of `MaterialApp` class? – Igor Kharakhordin Oct 07 '20 at 13:59
  • @IgorKharakhordin How if the navigatorKey has been used by `Catcher.navigatorKey`? – Jerry Feb 16 '21 at 08:26
  • Nice solution saved me a lot of time – Ehab Reda Apr 28 '22 at 04:01
  • 2
    If you're sure your navigatorKey will already have a context by the time you want to show the dialog, force unwrap your currentContext variable like so `context: navigatorKey.currentContext!` – Iván Yoed Jun 27 '22 at 23:48
  • 1
    Is there something you can do to ensure that currentContext is not `null` early in the initialization of your app? I get nervous every time I put a `!` in my code. – Clifton Labrum Aug 20 '22 at 20:11
  • 1
    I get error "No Material widget found. ListTile widgets require a Material widget ancestor." when I try to create a dialog with that currentContext. – queen3 Aug 23 '22 at 18:47
10

The dialog only needs the context to access it through an inherited navigateState. You can make your own modified dialog, or use my lib to do this.

https://pub.dev/packages/get

With it you can open dialog from anywhere in your code without context by doing this:

Get.dialog(SimpleDialog());
NecroMancer
  • 616
  • 11
  • 17
jonatas Borges
  • 1,947
  • 13
  • 17
  • That's not possible. You probably forgot to add "Get" to your MaterialApp. Change it to GetMaterialApp and everything will work. – jonatas Borges Oct 05 '20 at 19:58
  • like this GetMaterialApp.dialog(SimpleDialog()); – s.j Oct 06 '20 at 05:47
  • i tried this GetMaterialApp(title: UtilString.submit); getting compile time error. – s.j Oct 06 '20 at 05:55
  • No, on your main file – jonatas Borges Oct 06 '20 at 05:56
  • Controller controller = Get.find(); by this to show dialog ? – s.j Oct 06 '20 at 06:08
  • i trying to show success dialog in api success response . – s.j Oct 06 '20 at 06:09
  • 17
    dont force a 3rd party lib if it is not needed. see the answer with `final navigatorKey = GlobalKey();` – cs guy Jan 14 '21 at 15:59
  • Accepted answer is wrong? That's a huge overstatement to say the least. How come out of the numerous ways to achieve this, only `GetX`/`Get` (your) way is the only correct one? I respect the hard work done on `GetX` but you can't shove it down people throats. I'm surprised this was marked as the accepted answer. – om-ha Dec 26 '21 at 01:27
  • The correct answer (now deleted) said "There is no way to do this in Flutter". I'm not pushing GetX anywhere, I just mentioned that it's possible to do this, just like GetX does. The most voted answer came long after my answer, just compare the dates. – jonatas Borges Dec 27 '21 at 00:26
  • @jonatasBorges How will I close it without context ?? – L.Goyal Mar 03 '22 at 05:48
  • This answer states, "The accepted answer is wrong." However, this answer *is* the accepted answer. Is this like "this statement is false"? :) – Chuck Batson Oct 18 '22 at 16:15
1

Catch the exception where you make the getNews call if you use await, else use the catchError property of the Future.

ZeRj
  • 1,612
  • 14
  • 24
1

So you need a BuildContext to create a dialog but you don't have access to it. That's a common problem, you can refer to this StackOverflow question for one of the approaches to solve it (create a static dialog and show it from wherever you need).

Another approach you may consider is to pass the context when creating an async method or object as an argument. Make sure you null it when you're done.

Or you can make a flag (boolean) which becomes 'true' under a certain condition, and in one of the build() methods you always check that flag, and if it's 'true' - do your thing (show a dialog for instance).

Kirill Karmazin
  • 6,256
  • 2
  • 54
  • 42
-2
  1. Install GetX with: flutter pub add get
  2. create a dialog with Get.dialog
  3. add these line
Get.dialog(
      Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 40),
            child: Container(
              decoration: const BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.all(
                  Radius.circular(20),
                ),
              ),
              child: Padding(
                padding: const EdgeInsets.all(20.0),
                child: Material(
                  child: Column(
                    children: [
                      const Text("Dialog with GetX without context")
                      Row(
                        children: [
                          const SizedBox(width: 10),
                          Expanded(
                            child: ElevatedButton(
                              style: ElevatedButton.styleFrom(
                                minimumSize: const Size(0, 45),
                                primary: Colors.green,
                                onPrimary: const Color(0xFFFFFFFF),
                                shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(8),
                                ),
                              ),
                              onPressed: () {
                                Navigator.pop(Get.overlayContext!, true);
                              },
                              child: const Text(
                                'Cerrar',
                              ),
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );

done!

Blastfurnace
  • 18,411
  • 56
  • 55
  • 70
-3

Easiest way to show alert anywhere: Use this package link and enter these lines wherever you want to show alert:

QuickAlert.show( context: context, type: QuickAlertType.error, text: 'Error Message');

  • But your solution with QuickAlert needs a BuildContext context. The question was about "AlertDialog without context". – Stephan Feb 28 '23 at 20:16
  • 1
    I request you to please read the question carefully not just the heading. Secondly I didn't provide the context from the Build method of the class. I just provided the type of alert and the text. – user3107831 Mar 31 '23 at 10:25
  • void showAlert(type, text) { QuickAlert.show( context: context, type: type, text: text, ); } – user3107831 Mar 31 '23 at 10:25