KYflutterrookie
KYflutterrookie

Reputation: 47

Change the content of dialog in Flutter

After I clicked the button in the dialog, the content would change from a list of buttons into a form with textfields. However, I am frustrated in codes to achieve it.

Upvotes: 0

Views: 588

Answers (1)

untp
untp

Reputation: 191

You just need a stateful dialog and a bool state. Here is an example:

class MyDialog extends StatefulWidget {
  const MyDialog({Key? key}) : super(key: key);

  @override
  MyDialogState createState() => MyDialogState();
}

class MyDialogState extends State<MyDialog> {
  /// When this value is false, it shows list of buttons
  /// When this value is true, it shows list of textfields
  bool isForm = false;

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: const Text('AlertDialog Title'),
      // Here, we conditionally change content
      content: isForm
          ? Column(
              children: [
                TextFormField(),
                TextFormField(),
                TextFormField(),
                TextFormField(),
              ],
            )
          : Column(
              children: [
                TextButton(onPressed: () {}, child: Text('Button')),
                TextButton(onPressed: () {}, child: Text('Button')),
                TextButton(onPressed: () {}, child: Text('Button')),
                TextButton(onPressed: () {}, child: Text('Button')),
              ],
            ),
      actions: [
        TextButton(
          // Here isForm is switched to change the content
          onPressed: () => setState(() => isForm = !isForm),
          child: const Text('Switch'),
        ),
        TextButton(
          onPressed: () => Navigator.pop(context),
          child: const Text('Cancel'),
        ),
        TextButton(
          onPressed: () => Navigator.pop(context, true),
          child: const Text('OK'),
        ),
      ],
    );
  }
}

Use it with showDialog(context: context, builder: (context) => MyDialog())

Upvotes: 1

Related Questions