Flutter – How to call SetState in Alert Dialog (2022)

We will see in this article how to call setstate in Alert Dialogs in Flutter. First, we will create a simple button on any screen and will open an alert dialog by clicking that button. We will use a checkbox in that dialog and will try to change his state by using the setstate.

Let’s move to our topic:

Create a simple Stateful widget with DialogButton or whatever that you want, and create a button in this screen and will add the texts ‘Open Dialog’ in that button.

class _DialogButtonState extends State<DialogButton> {
  @override
  Widget build(BuildContext context) {
    final double height = MediaQuery.of(context).size.height;
    final double width = MediaQuery.of(context).size.width;
    return Scaffold(
      backgroundColor: const Color(0xffF2F2F2),
      body: SizedBox(
        height: height,
        width: width,
        child: Center(
          child: Container(
            height: 50.0,
            width: double.infinity,
            margin: const EdgeInsets.symmetric(horizontal: 24.0),
            child: ElevatedButton(
              onPressed: (){},
              child: const Center(
                child: Text("Open Dialog",
                style: TextStyle(
                  fontSize: 20.0,
                ),
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}

The output should be like this:

Now, when we click on the button then an alert dialog will occur. So, for that we will write the code in the way:

final bool _isChecked = false;


Future _openDialog() => showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text("SetState In Dialog"),
        content: CheckboxListTile(
          controlAffinity: ListTileControlAffinity.leading,
          title: const Text("Hello"),
          value: _isChecked,
          onChanged: (value){

          },
        ),
        actions: [
          TextButton(
              onPressed: (){
                Navigator.of(context).pop();
              },
              child: const Text("SUBMIT"),
          ),
        ],
      ),
  );

After this, we call this _openDialog() inside the button property onPressed: (){}, and the output will be like this…

But now the problem is here that when we click the checkbox in the alert dialog the alert dialog state is not changing. So, what we will do? We will wrap the AlertDialog inside the StatefulBuilder. Because when we wrap the alert dialog inside the statefulBuilder then inside statefulBuilder we can change anything easily by using the setstate…

Let’s write the code:

  Future _openDialog() => showDialog(
      context: context,
      builder: (context) => StatefulBuilder(
        builder: (context, setState) {
          return AlertDialog(
            title: const Text("SetState In Dialog"),
            content: CheckboxListTile(
              controlAffinity: ListTileControlAffinity.leading,
              title: const Text("Hello"),
              value: _isChecked,
              onChanged: (value){
                setState(() {
                  _isChecked = value!;
                });
              },
            ),
            actions: [
              TextButton(
                  onPressed: (){
                    Navigator.of(context).pop();
                  },
                  child: const Text("SUBMIT"),
              ),
            ],
          );
        }
      ),
  );

we will update the _openDialog function in this way and our setState will work inside the alert dialog.

Read this article: How to make transparent appbar in Flutter

Flutter Docs:

Complete Code:

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Dialog with SetState',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      /*home: SplashScreen(
          isSvg: false,
          iconPath: 'assets/bg.jpg',
          onPressed: (){},
      ),*/
      //home: const Appbar(),
      home: const DialogButton(),
    );
  }
}


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

  @override
  State<DialogButton> createState() => _DialogButtonState();
}

class _DialogButtonState extends State<DialogButton> {

  bool _isChecked = false;

  @override
  Widget build(BuildContext context) {
    final double height = MediaQuery.of(context).size.height;
    final double width = MediaQuery.of(context).size.width;
    return Scaffold(
      backgroundColor: const Color(0xffF2F2F2),
      body: SizedBox(
        height: height,
        width: width,
        child: Center(
          child: Container(
            height: 50.0,
            width: double.infinity,
            margin: const EdgeInsets.symmetric(horizontal: 24.0),
            child: ElevatedButton(
              onPressed: (){
                _openDialog();
              },
              child: const Center(
                child: Text("Open Dialog",
                style: TextStyle(
                  fontSize: 20.0,
                ),
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }

  Future _openDialog() => showDialog(
      context: context,
      builder: (context) => StatefulBuilder(
        builder: (context, setState) {
          return AlertDialog(
            title: const Text("SetState In Dialog"),
            content: CheckboxListTile(
              controlAffinity: ListTileControlAffinity.leading,
              title: const Text("Hello"),
              value: _isChecked,
              onChanged: (value){
                setState(() {
                  _isChecked = value!;
                });
              },
            ),
            actions: [
              TextButton(
                  onPressed: (){
                    Navigator.of(context).pop();
                  },
                  child: const Text("SUBMIT"),
              ),
            ],
          );
        }
      ),
  );

}

Output:

So, in this way you can call SetState in Alert Dialog

Flutter

Read these Articles:

Flutter – Splash Screen Custom Widget

Top 10 highest paid skills on Fiverr in 2022

Top 15 websites for free stock photos

Share