How to refresh an AlertDialog in Flutter?

前端 未结 5 2365
萌比男神i
萌比男神i 2020-11-27 13:54

Currently, I have an AlertDialog with an IconButton. The user can click on the IconButton, I have two colors for each click. The problem is that I

5条回答
  •  爱一瞬间的悲伤
    2020-11-27 14:53

    The docs suggest that you use a StatefulBuilder in the content section of the AlertDialog. Even the StatefulBuilder docs actually have an example with a dialog.

    What it does is provide you with a new context and setState function to rebuild when needed.

    The sample code from the docs:

    showDialog(
      context: context,
      builder: (BuildContext context) {
    
        int selectedRadio = 0; // Declare your variable outside the builder
    
        return AlertDialog( 
          content: StatefulBuilder(  // You need this, notice the parameters below:
            builder: (BuildContext context, StateSetter setState) {
              return Column(  // Then, the content of your dialog.
                mainAxisSize: MainAxisSize.min,
                children: List.generate(4, (int index) {
                  return Radio(
                    value: index,
                    groupValue: selectedRadio,
                    onChanged: (int value) {
                      // Whenever you need, call setState on your variable
                      setState(() => selectedRadio = value);
                    },
                  );
                }),
              );
            },
          ),
        );
      },
    );
    

    And as I mentioned, this is what is said on the showDialog docs:

    [...] The widget returned by the builder does not share a context with the location that showDialog is originally called from. Use a StatefulBuilder or a custom StatefulWidget if the dialog needs to update dynamically.

提交回复
热议问题