How to Manage alert dialog by clicking other areas of Screen in Flutter?

Issue

I have an activity in my app. I am using Alert Dialog. when I reach to this activity and Alert Dialog is open, while I click other area of screen it disappears, but the problem is that while I want to click insides of any text field it reappear again and over again. I want this like once it disappears new reappears again until I go to other activity and return to this activity again. I am new to Flutter I am facing this problem from few days, I searched this problem many times but not found and solution to resolve it, any one who can help me, thanks in advance.
Code

    import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'bottomnavigationbar.dart';

class Contact extends StatefulWidget {
  @override
  _ContactState createState() => _ContactState();
}

class _ContactState extends State<Contact> {
  @override
  Widget build(BuildContext context) {
    AlertDialog dialog = new AlertDialog(
      content: Container(
        width: 260.0,
        height: 187.0,
        decoration: new BoxDecoration(
          shape: BoxShape.rectangle,
          //  color: const Color(0xFFFFFF),
          borderRadius: new BorderRadius.all(new Radius.circular(50.0)),
        ),
        child: Column(
          children: <Widget>[
            Padding(
              padding: EdgeInsets.all(1),
            ),
            Container(
              child: GestureDetector(
                onTap: () {
//                Route route =
//                    MaterialPageRoute(builder: (context) => Payment1());
//                Navigator.pushReplacement(context, route);
                  //  Navigator.pushNamed(context, "myRoute");
                },
                child: new Text(
                  "For Bikes-979578-6541",
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    color: Colors.red,
                    fontSize: 18,
                    //  fontWeight: FontWeight.w700,
                  ),
                ),
              ),
            ),
            Padding(
              padding: EdgeInsets.all(1),
            ),
            Divider(
              thickness: 1.5,
            ),
            Padding(
              padding: EdgeInsets.all(1),
            ),
            Container(
              child: GestureDetector(
                onTap: () {
//                Route route =
//                    MaterialPageRoute(builder: (context) => Payment1());
//                Navigator.pushReplacement(context, route);
                  //  Navigator.pushNamed(context, "myRoute");
                },
                child: new Text(
                  "For Boats-979-541-3607",
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    color: Colors.red,
                    fontSize: 18,
                    //fontWeight: FontWeight.w700,
                  ),
                ),
              ),
            ),
            Padding(
              padding: EdgeInsets.all(1),
            ),
            Divider(
              thickness: 1.5,
            ),
            Padding(
              padding: EdgeInsets.all(1),
            ),
            Container(
              child: GestureDetector(
                onTap: () {
//                Route route =
//                    MaterialPageRoute(builder: (context) => Payment1());
//                Navigator.pushReplacement(context, route);
                  //  Navigator.pushNamed(context, "myRoute");
                },
                child: new Text(
                  "redtiderentals@yahoo.com",
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    color: Colors.red,
                    fontSize: 18,
                    // fontWeight: FontWeight.w700,
                  ),
                ),
              ),
            ),
            Padding(
              padding: EdgeInsets.all(1),
            ),
            Divider(
              thickness: 1.5,
            ),
            Padding(
              padding: EdgeInsets.all(1),
            ),
            Container(
              child: GestureDetector(
                onTap: () {
//                Route route =
//                    MaterialPageRoute(builder: (context) => Payment1());
//                Navigator.pushReplacement(context, route);
                  //  Navigator.pushNamed(context, "myRoute");
                },
                child: new Text(
                  "Follow Us on Facebook!",
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    color: Colors.red,
                    fontSize: 18,
                    //  fontWeight: FontWeight.w700,
                  ),
                ),
              ),
            ),
            Padding(
              padding: EdgeInsets.all(1),
            ),
            Divider(
              thickness: 1.5,
            ),
            Padding(
              padding: EdgeInsets.all(1),
            ),
            Container(
              child: GestureDetector(
                onTap: () {
                  //    Navigator.pop(dialog);
//                Route route =
//                    MaterialPageRoute(builder: (context) => Payment1());
//                Navigator.pushReplacement(context, route);
                  //  Navigator.pushNamed(context, "myRoute");
                  //   Navigator.of(context).pop(false),
                },
                child: new Text(
                  "Done",
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    color: Colors.red,
                    fontSize: 18,
                    //fontWeight: FontWeight.w700,
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
    Future.delayed(
      Duration.zero,
      () => showDialog(
          context: context, builder: (BuildContext context) => dialog),
    );

    TextStyle style = TextStyle(
        fontFamily: 'Montserrat', color: Colors.white, fontSize: 16.0);

    return Scaffold(
      appBar: AppBar(
        title: Text("Contact"),
        centerTitle: true,
        actions: <Widget>[
          new IconButton(
            icon: new Icon(
              Icons.more_horiz,
              size: 35,
              color: Colors.white,
            ),
            //  tooltip: 'Closes application',
            //   onPressed: () => exit(0),
          ),
        ],
      ),
      body: SingleChildScrollView(
        child: Container(
          padding: EdgeInsets.all(1),
          color: Colors.black,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              Container(
                width: MediaQuery.of(context).size.width,
                height: MediaQuery.of(context).size.width / 1.6,
                //  constraints: BoxConstraints.expand(),
                decoration: BoxDecoration(
                  image: DecorationImage(
                      image: AssetImage("images/contactpage.png"),
                      fit: BoxFit.cover),
                ),
              ),
              Padding(
                padding: EdgeInsets.all(8),
              ),
              Text(
                "Contact Info",
                style: TextStyle(
                  color: Colors.red,
                  fontSize: 20,
                  fontWeight: FontWeight.w400,
                ),
              ),
              Padding(
                padding: EdgeInsets.all(8),
              ),
              Divider(
                color: Colors.white,
                indent: 40,
                endIndent: 40,
              ),
              Padding(
                padding: EdgeInsets.all(8),
              ),
              Container(
                  padding: EdgeInsets.all(16),
                  child: Column(
                    //mainAxisAlignment: MainAxisAlignment.center,

                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        "We are a locally owned. family run business providing equipment rentals in Matagorda Country. We are dedicated to making your experience with us go as smoothly as possible. Fill out the form below or call us if you have any questions or concerns.",
                        style: TextStyle(
                          color: Colors.white70,
                          fontSize: 15,
                          fontWeight: FontWeight.w400,
                        ),
                      ),
                      Text(
                        "Mobile No:",
                        style: TextStyle(
                            color: Colors.white,
                            fontSize: 20,
                            fontWeight: FontWeight.w400),
                      ),
                      TextField(
                        style: style,
                        maxLength: 30,
                        cursorColor: Colors.red,
                        textAlign: TextAlign.left,
                        keyboardType: TextInputType.number,
                        decoration: InputDecoration(
                          hintText: 'Enter your mobile number',
                          hintStyle:
                              TextStyle(fontSize: 16, color: Colors.white),
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(8),
                            borderSide: BorderSide(
                              width: 0,
                              style: BorderStyle.none,
                            ),
                          ),
                          filled: true,
                          fillColor: Color(0xFF1E1E1E),
                          contentPadding: EdgeInsets.all(16),
                        ),
                      ),
                      Text(
                        "Email:",
                        style: TextStyle(
                            color: Colors.white,
                            fontSize: 20,
                            fontWeight: FontWeight.w400),
                      ),
                      TextField(
                        style: style,
                        maxLength: 16,
                        cursorColor: Colors.red,
                        textAlign: TextAlign.left,
                        keyboardType: TextInputType.emailAddress,
                        decoration: InputDecoration(
                          hintText: 'Enter your email',
                          hintStyle:
                              TextStyle(fontSize: 16, color: Colors.white),
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(8),
                            borderSide: BorderSide(
                              width: 0,
                              style: BorderStyle.none,
                            ),
                          ),
                          filled: true,
                          fillColor: Color(0xFF1E1E1E),
                          contentPadding: EdgeInsets.all(16),
                        ),
                      ),
                      Text(
                        "Description:",
                        style: TextStyle(
                            color: Colors.white,
                            fontSize: 20,
                            fontWeight: FontWeight.w400),
                      ),
                      TextField(
                        keyboardType: TextInputType.text,
                        maxLines: 8,
                        maxLength: 1000,
                        style: style,
                        cursorColor: Colors.red,
                        textAlign: TextAlign.left,
                        decoration: InputDecoration(
                          hintText: 'Enter Description Here',
                          hintStyle:
                              TextStyle(fontSize: 16, color: Colors.white),
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(8),
                            borderSide: BorderSide(
                              width: 0,
                              style: BorderStyle.none,
                            ),
                          ),
                          filled: true,
                          fillColor: Color(0xFF1E1E1E),
                          contentPadding: EdgeInsets.all(16),
                        ),
                      ),
                      Material(
                        elevation: 5.0,
                        borderRadius: BorderRadius.circular(30.0),
                        color: Colors.red,
                        child: MaterialButton(
                          minWidth: MediaQuery.of(context).size.width,
                          padding: EdgeInsets.fromLTRB(20.0, 15.0, 20.0, 15.0),
                          onPressed: () {
//                        Route route =
//                        MaterialPageRoute(builder: (context) => Payment2());
//                        Navigator.pushReplacement(context, route);
                          },
                          child: Text("Submit",
                              textAlign: TextAlign.center,
                              style: style.copyWith(
                                  color: Colors.white,
                                  fontWeight: FontWeight.w800)),
                        ),
                      ),
                    ],
                  ))
            ],
          ),
        ),
      ),
      bottomNavigationBar: BottomNavigation(),
    );
  }
}

Video link
[Problem Video][1]
[1]: https://drive.google.com/file/d/11i4R9DZAImO8CGw7TwOwQ0wbXXn9yHLr/view?usp=sharing

Solution

Flutter got a showDialog() method particularly for dialog widget. You may put the AlertDialog widget inside and call the showDialog() method in initState() which will be called exactly once when a stateful widget is created so it won’t be called during rebuilding. If you want to dismiss the dialog when tapping other regions, set the barrierDismissible parameter of showDialog() method to true.

You just need to modify the _ContactState class like this:

class _ContactState extends State<Contact> {
        
     @override
      void initState() {
        super.initState();
        Future.delayed(
            Duration.zero,
            () => showDialog(
                  context: context,
                  barrierDismissible: true, 
                  builder: (_) => AlertDialog(
                   // content

               ),
            )   
         );
       }
        
     @override
     Widget build(BuildContext context) {
       //your original code without the AlertDialog widget
     }
}

==========================
. UPDATED

I made some changes in this code.Now it is working fine 👌

Answered By – Kennith

Answer Checked By – Pedro (FlutterFixes Volunteer)

Leave a Reply

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