简体   繁体   中英

close Simple Dialog in flutter when setState needs to called

I'm having a problem calling Navigator.of(context).pop() on my onPressed property in SimpleDialogOption widget. I need to set the state and dismiss the dialog. But calling setState is preventing my dialog to close. Without setState the dialog closes. Here is my dialog

WidgetsBinding.instance.addPostFrameCallback((_) {
                          showDialog(
                              builder: (BuildContext context) {
                                return SimpleDialog(
                                  children: _children(suburbs),
                                  backgroundColor: Colors.white,
                                  title: Text('Pick your suburb'),
                                );
                              },
                              context: context);
                        });

and the method I use for the list of the Dialog:

List<Widget> _children(List<Suburb> suburbs) {
    return suburbs
        .map((suburb) => SimpleDialogOption(
            onPressed: () {
              print('@@@@@@@@@@@@@@@@@@@@@');
              setState(() {
                postcode = suburb.name;
              });
              Navigator.of(context).pop();
            },
            child: Text(suburb.name)))
        .toList();
  }

you can await until the return value comes from the navigator.pop, and then call a setState

     WidgetsBinding.instance.addPostFrameCallback((_) async {

        postcode = await showDialog(
            builder: (BuildContext context) {
              return SimpleDialog(
                children: _children(suburbs),
                backgroundColor: Colors.white,
                title: Text('Pick your suburb'),
              );
            },
            context: context);

        setState(() {
          postcode;
        });

    });



    List<Widget> _children(List<Suburb> suburbs) {
        return suburbs
            .map((suburb) => SimpleDialogOption(
            onPressed: () {
              print('@@@@@@@@@@@@@@@@@@@@@');
              Navigator.of(context).pop(suburb.name);
            },
            child: Text(suburb.name)))
            .toList();
      }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM