How do you use a TextField in Flutter?

Although there are different text input widget in flutter, yet the TextField is the most commonly used.

The TextField is a material design widget. Therefore, one of its ancestors should be MaterialApp.

By default, a TextField is decorated with an underline. In addition we can add a label, icon, inline hint text, and error text with the help of decoration property.

What does decoration do?

Let’s see an image to get an idea.

Text Field Flutter example
Text Field Flutter example

By default, decoration property draws a divider below the text field as we can see in the above image.

Certainly, the role of the decoration property doesn’t end here. We can control the other decoration parts.

For instance, we can add a label or an icon.

To get an idea, let’s see the first code example of the above text field.

TextField(
                    decoration: InputDecoration(
                      border: OutlineInputBorder(),
                      labelText: 'ITEM',
                      suffixStyle: TextStyle(
                        fontSize: 50,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    controller: titleController,
                  ),

After the decoration the most important property or parameter of a TextField is controller.

Why controller is so important?

Let’s try to understand the concept and role of text field.

Firstly, the TextField is a material design text input widget. As a result, user should be able to type text and add that inputs to a local or remote storage.

Naturally, the TextField in Flutter is the most commonly used text input widget that allows users to collect inputs from the keyboard into an app. Without the controller we cannot do that.

Secondly, controller is the most important property because it controls the selection, composing region, and finally, it observes the changes.

For example, take a look at the second image.

Text Field Flutter Submitting data
Text Field Flutter Submitting data

To submit data to our local storage, we need to declare controllers beforehand.

final titleController = TextEditingController();
  final amountController = TextEditingController();

Meanwhile we have defined a data model also in our model sub-directory.

import 'package:flutter/foundation.dart';

class ExpenseList {
  String id;
  String title;
  double amount;
  DateTime date;

  ExpenseList({
    @required this.id,
    @required this.title,
    @required this.amount,
    @required this.date,
  });
}

Next, inside our flutter app, we’ve used a callback and pass the two text controllers.

TextButton(
                    onPressed: () {
                      addTaskAndAmount(
                        titleController.text,
                        double.parse(amountController.text),
                      );
                    },
                    child: Text(
                      'SUBMIT',
                      style: TextStyle(
                        fontSize: 25,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),

Now, we can define the required callback quite easily inside our stateful widget.

class _ExpenseFirstPageState extends State<ExpenseFirstPage> {
  final List<ExpenseList> expenseList = [];

  void addTaskAndAmount(String title, double amount) {
    final expense = ExpenseList(
      id: DateTime.now().toString(),
      title: title,
      amount: amount,
      date: DateTime.now(),
    );
    setState(() {
      expenseList.add(expense);
    });
  }

  void deleteExpenseList(String id) {
    setState(() {
      expenseList.removeWhere((element) => element.id == id);
    });
  }
....
//code is incomplete for brevity, please visit the GitHub repository for full code

As a result, we can add the input data to our local storage and it will display automatically.

Text Field Flutter data submitted
Text Field Flutter data submitted

To sum up, we’ll take a look at another important property of the TextField.

How can I get data from multiple TextField in flutter?

We know that the text field calls the onChanged callback whenever the user changes the text in the field.

However, there is another important property onSubmitted callback.

When a use has finished typing in the text field, by pressing the submit button as shown on the above code snippet, or pressing the soft keyboard, the text field immediately calls the onSubmitted callback.

To get an idea, we can take a look at the second text field in our example app.

TextField(
                    decoration: InputDecoration(
                      border: OutlineInputBorder(),
                      labelText: 'AMOUNT',
                      suffixStyle: TextStyle(
                        fontSize: 50,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    controller: amountController,
                    onSubmitted: (String value) async {
                      await showDialog<void>(
                        context: context,
                        builder: (BuildContext context) {
                          return AlertDialog(
                            title: const Text('Thanks!'),
                            actions: <Widget>[
                              TextButton(
                                onPressed: () {
                                  Navigator.pop(context);
                                },
                                child: const Text('OK'),
                              ),
                            ],
                          );
                        },
                      );
                    },
                  ),

As a result, when the user is done typing and press the submit button, the onSubmitted callback fires a AlertDialog widget.

Consequently, we can see an alert on the screen.

Text Field Flutter alert dialog box opened
Text Field Flutter alert dialog box opened

Besides these properties of a text field, we can integrate the TextField into a Form with other FormField widgets. And to do that we can use TextFormField.

For most applications the onSubmitted callback will be sufficient for reacting to user input.

To sum up, we can have an idea of how the TextField widget works takes inputs from the users. Moreover, we can store that value with the help of text controller in our local storage.

What Next?

Books at Leanpub

Books in Apress

My books at Amazon

GitHub repository

Technical blog

Twitter


Posted

in

, , , ,

by

Comments

4 responses to “How do you use a TextField in Flutter?”

  1. […] Since a card widget represents some related information, let us represent information about our expense list that we’ve been building in our previous article. […]

  2. […] planned to add a list of words, so we need to have the following part of the code where we have a text field, text editing controller and a mechanism that will add words to the […]

  3. […] next challenge is to show a text field to the user so that she can type any text and press the […]

  4. […] It depends on us. As in the above code, we have used a TextField widget. […]

Leave a Reply