How to Refresh an AlertDialog In Flutter

How to Refresh an AlertDialog In Flutter?

Sometimes an application needs the user’s confirmation to make changes in data. generally one of the ways to get confirmation from the user is to display Alert Dialog. In this article, we will be discussing How to Refresh an AlertDialog In Flutter?

In this instructive blog post, explore the process of refreshing an AlertDialog in Flutter, enabling you to update its content dynamically. Discover efficient techniques and code snippets that allow you to refresh the information displayed within an AlertDialog based on user actions or real-time data changes. Whether you’re building a form, a settings page, or any other scenario where information updates are crucial, this tutorial will guide you step-by-step through the process. Enhance user experience and ensure your AlertDialogs reflect the latest data by mastering the art of refreshing them in Flutter. Let’s dive in and create dynamic and responsive dialogs today.

Know How to Refresh an AlertDialog In Flutter?

Use StatefulBuilder to use setState inside Dialog and update widgets only inside of it. Consider a code snippet like the below:

ialog and update Widgets only inside of it.

showDialog(
  context: context,
  builder: (context) {
    String contentText = "Content of Dialog";
    return StatefulBuilder(
      builder: (context, setState) {
        return AlertDialog(
          title: Text("Title of Dialog"),
          content: Text(contentText),
          actions: <Widget>[
            FlatButton(
              onPressed: () => Navigator.pop(context),
              child: Text("Cancel"),
            ),
            FlatButton(
              onPressed: () {
                setState(() {
                  contentText = "Changed Content of Dialog";
                });
              },
              child: Text("Change"),
            ),
          ],
        );
      },
    );
  },
)

Currently to retrieve the value of Dialog we can use

showDialog().then((val){
setState (() {}); 
print (val);
});

Example 1st screen

onPressed: () { 
   showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) {
        return AddDespesa();
      }).then((val) {
        setState(() {});
        print(val);
       }
   );
  }

2nd screen

AlertDialog(
    title: Text("Sucesso!"),
    content: Text("Gasto resgristrado com sucesso"),
    actions: <Widget>[
    FlatButton(
      child: Text("OK"),
      onPressed: () {
         Navigator.pop(context, true);
      },
     ),
   ],
 );

Will be printed true.

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.

Tip of the day

Clean up your code with Dart 2.3’s Spread Operator

” Dart is the programming language used to code Flutter apps. The recent Dart 2.3 update introduced the Spread operator, which can be used for conditional UI widgets. These are especially recommended for nested conditional UI Widget “: dart-2-language-features

Stack(
     alignment: Alignment.center,
     children: <Widget>[
     if (_visible) ...[
          spaceAnim(),
          //Nested if-else
          if (_visible) ...[
              spaceAnim(),
          ]else ...[
              galaxyAnim(),
           ],
     ]else ...[
         galaxyAnim(),
     ],
  ],
),

It also provides an easy way to insert multiple values into a collection.

var list = [1, 2, 3];
var list2 = [0, ...list];
assert(list2.length == 4);

The Sample code will look like the below:

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<Widget>.generate(4, (int index) {
              return Radio<int>(
                value: index,
                groupValue: selectedRadio,
                onChanged: (int value) {
                  // Whenever you need, call setState on your variable
                  setState(() => selectedRadio = value);
                },
              );
            }),
          );
        },
      ),
    );
  },
);

As per 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.

First, you need to use StatefulBuilder. Then I am setting _setState variable, which even could be used outside StatefulBuilder, to set a new state.

StateSetter _setState;
String _demoText = "test";

showDialog(
  context: context,
  builder: (BuildContext context) {

    return AlertDialog( 
      content: StatefulBuilder(  // You need this, notice the parameters below:
        builder: (BuildContext context, StateSetter setState) {
          _setState = setState;
          return Text(_demoText);
        },
      ),
    );
  },
);

_setState is used the same way as the setState method. For example like this:

_setState(() {
    _demoText = "new test text";
});

Conclusion:

Thanks for being with us on a Flutter Journey!!!

In this article, we have been through how to refresh an alertdialog in flutter?

Do let us know if you need any assistance with flutter development.?? We would love to assist you.

FlutterAgency is our portal Platform dedicated to Flutter Technology and Flutter Developers. The portal is full of cool resources from Flutter like Flutter Widget Guide, Flutter Projects, Code libs and etc.

FlutterAgency USA is one of the most popular online portals dedicated to Flutter Technology and daily thousands of unique visitors come to this portal to enhance their knowledge of Flutter.

Nirali Patel

Written by Nirali Patel

Nirali Patel is a dedicated Flutter developer with over two years of experience, specializing in creating seamless mobile applications using Dart. With a passion for crafting user-centric solutions, Nirali combines technical proficiency with innovative thinking to push the boundaries of mobile app development.

1 comment

Leave a comment

Your email address will not be published. Required fields are marked *

Discuss Your Project

Connect with Flutter Agency's proficient skilled team for your app development projects across different technologies. We'd love to hear from you! Fill out the form below to discuss your project.

Have Project For Us

Get in Touch

"*" indicates required fields

ready to get started?

Fill out the form below and we will be in touch soon!

"*" indicates required fields