AlertDialog with a TextField in Flutter

In this tutorial, you will learn how to create an AlertDialog with a TextField in Flutter. We will go through all the steps and at the end, you will have a complete code example that displays an alert dialog with a text field.

Creating AlertDialog

The basic code to create an AlertDialog widget with a single TextField looks like this.

AlertDialog( 
        title: Text('TextField in Dialog'), 
        content: TextField( 
          onChanged: (value) { }, 
          controller: _textFieldController, 
          decoration: InputDecoration(hintText: "Text Field in Dialog"), 
        ),
    ),

To make the above code snippet work and to actually present an alert dialog, we will need to put it into a function that we can later call.

Future<void> _displayTextInputDialog(BuildContext context) async {
  return showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: Text('TextField in Dialog'),
          content: TextField(
            onChanged: (value) {
     
            },
            controller: _textFieldController,
            decoration: InputDecoration(hintText: "Text Field in Dialog"),
          ),

        );
      });
}

Alert window example in Flutter

You may have noticed that there is a “controller” property set to “_textFieldController“, as you will see in the full example below the Text Editing Controller is a controller that is used for the editable text field. This means whenever a user modifies the text field associated with the controller, updates the value, then the controller will notify its listeners. Text Editing Controller can be used to provide an initial value to a text field.

As you can see in the image we are getting the Text Field displayed in the alert dialog but in this way, it is not of much use to us. In order to use it in our app, we need action to handle the event. Luckily alert dialog has a property called “actions” where you can handle the event.

Handle Events

Next, let’s learn how to handle an event when a button in the alert dialog is pressed. In the “actions” property of alert dialog, we will place a FlatButton. When this button is tapped, the onPressed event will trigger and will store the value of the TextField in a String. Have a look at the code snippet below:

Future<void> _displayTextInputDialog(BuildContext context) async {
   return showDialog(
       context: context,
       builder: (context) {
         return AlertDialog(
           title: Text('TextField in Dialog'),
           content: TextField(
             onChanged: (value) {
               setState(() {
                 valueText = value;
               });
             },
             controller: _textFieldController,
             decoration: InputDecoration(hintText: "Text Field in Dialog"),
           ),
           actions: <Widget>[
             FlatButton(
               color: Colors.green,
               textColor: Colors.white,
               child: Text('OK'),
               onPressed: () {
                 setState(() {
                   codeDialog = valueText;
                   Navigator.pop(context);
                 });
               },
             ),
  
           ],
         );
       });
 }

If you run the code snippet above, the alert window will look like the one in the picture below.

AlertDialog with a TextField example in Flutter

 

Adding Cancel Button

Let’s learn how to add a Cancel button and handle an event when the cancel button is tapped.  When the cancel button is tapped, we want to dismiss the alert window. In Flutter it is done with the help of Navigator object. When the user taps on the cancel button, we need to call the pop(context) function on the Navigator object as is illustrated in the code example below.

Navigator.pop(context);

Below is a code example of how it is done in the app code.

Future<void> _displayTextInputDialog(BuildContext context) async {
  return showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: Text('TextField in Dialog'),
          content: TextField(
            onChanged: (value) {
              setState(() {
                valueText = value;
              });
            },
            controller: _textFieldController,
            decoration: InputDecoration(hintText: "Text Field in Dialog"),
          ),
          actions: <Widget>[
            FlatButton(
              color: Colors.red,
              textColor: Colors.white,
              child: Text('CANCEL'),
              onPressed: () {
                setState(() {
                  Navigator.pop(context);
                });
              },
            ),
            FlatButton(
              color: Colors.green,
              textColor: Colors.white,
              child: Text('OK'),
              onPressed: () {
                setState(() {
                  codeDialog = valueText;
                  Navigator.pop(context);
                });
              },
            ),

          ],
        );
      });
}

Flutter AlertDialog with a TextField and two buttons

 

Complete Code Example

Now that we have discussed different code snippets separately, let’s put everything into one complete app code example.

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Alert Dialog',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Alert Dialog'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  TextEditingController _textFieldController = TextEditingController();

  Future<void> _displayTextInputDialog(BuildContext context) async {
    return showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            title: Text('TextField in Dialog'),
            content: TextField(
              onChanged: (value) {
                setState(() {
                  valueText = value;
                });
              },
              controller: _textFieldController,
              decoration: InputDecoration(hintText: "Text Field in Dialog"),
            ),
            actions: <Widget>[
              FlatButton(
                color: Colors.red,
                textColor: Colors.white,
                child: Text('CANCEL'),
                onPressed: () {
                  setState(() {
                    Navigator.pop(context);
                  });
                },
              ),
              FlatButton(
                color: Colors.green,
                textColor: Colors.white,
                child: Text('OK'),
                onPressed: () {
                  setState(() {
                    codeDialog = valueText;
                    Navigator.pop(context);
                  });
                },
              ),

            ],
          );
        });
  }

  String codeDialog;
  String valueText;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: (codeDialog == "123456") ? Colors.green : Colors.white,
      appBar: AppBar(
        backgroundColor: Colors.teal,
        title: Text('Alert Dialog'),
      ),
      body: Center(
        child: FlatButton(
          color: Colors.teal,
          textColor: Colors.white,
          onPressed: () {
            _displayTextInputDialog(context);
          },
          child: Text('Press For Alert'),
        ),
      ),
    );
  }
}

If you build and run the above code example on Android Emulator, the will look and work as illustrated with the images below.

When an alert window is presented and the user inputs and submits “123456”, then the background color will turn green, otherwise it will turn white.

                    

I hope this Flutter tutorial is helpful to you. If you are interested in learning Flutter, please check other Flutter tutorials on this site. Some of them have video tutorials included.

Happy learning!


Leave a Reply

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

Free Video Lessons

Enter your email and stay on top of things,

Subscribe!