In Flutter, if you need to update the content of AlertDialog, the common approach is to call setState after updating the state to trigger UI rebuild. Here is a concrete example demonstrating how to update content within the AlertDialog.
Suppose we have an AlertDialog displaying a number, which is a state variable. We want to provide a button in the dialog that, when clicked, increments the number and updates the number in the dialog instantly.
Here is a simple implementation:
dartimport 'package:flutter/material.dart'; void main() { runApp(MaterialApp(home: HomePage())); } class HomePage extends StatefulWidget { _HomePageState createState() => _HomePageState(); } class _HomePageState extends State<HomePage> { int _count = 0; void _showDialog() { showDialog( context: context, builder: (BuildContext context) { return StatefulBuilder( builder: (context, setState) { return AlertDialog( title: Text('Counter'), content: Text('The count is $_count'), actions: <Widget>[ TextButton( child: Text('Add'), onPressed: () { setState(() { _count++; }); }, ), TextButton( child: Text('Close'), onPressed: () { Navigator.of(context).pop(); }, ) ], ); }, ); }, ); } Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text('AlertDialog Refresh Example')), body: Center( child: ElevatedButton( onPressed: _showDialog, child: Text('Show Dialog'), ), ), ); } }
In this example, we use the StatefulBuilder widget, which allows us to update the state within the AlertDialog. Each time the Add button is clicked, setState is called, which causes the builder method of StatefulBuilder to be re-executed, thereby updating the number displayed in the AlertDialog.
Note that the setState function provided by StatefulBuilder only rebuilds the UI within its scope, rather than rebuilding the entire page. This makes the update more efficient and limited to the dialog's content.
With this approach, we can conveniently update dynamic content within the AlertDialog without having to close and reopen the dialog.