Flutter - How to use TextField or TextEditingController

In flutter, TextField/TextFormField is the most usable widget. that allow to get various types of information from the user. this information may have email, name, mobile, etc. So in this tutorial, we going to learn how to use TextField in our app. Whenever the end user modifies the text field value, the controller notifies its listeners for saving the latest value. TextEditingController also allows you to modify the text and selection. In this case, the controller will notify the text field so that it can update the TextField.

How to Initialize TextEditingController:

First, we create an object of TextEditingController with an initial value like below.

 final textEditingController = TextEditingController(text: "Errorgram")

 

Binding to TextField or TextFormField:

Now we need to bind TextEditingController with TextField or TextFormField like below.

TextFormField(
    controller: textEditingController,
    decoration: InputDecoration(
        labelText: 'First Name'
    ),
  ),

 

Get text and selection Values :

Frequently we need to get text from TextField or TextFormField for store data somewhere.We can get like below.

textEditingController.text

If you need to get information about TextSelection use the selection property of TextEditingController.

textEditingController.selection

 

Full Example : 


class Errorgram extends StatefulWidget {
  const Errorgram({Key? key, required this.title}) : super(key: key);
  final String title;

  @override
  State<Errorgram> createState() => _ErrorgramState();
}

class _ErrorgramState extends State<Errorgram> {
  final textEditingController = TextEditingController(text: "Errorgram");
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text(
          "Errorgram",
          style: TextStyle(color: Colors.black),
        ), //Change color here
      ),
      body: Container(
        margin: EdgeInsets.only(left: 10, right: 10),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            TextFormField(
              controller: textEditingController,
              decoration: InputDecoration(
                  labelText: 'First Name'
              ),
            ),
          ],
        ),
      ),
    );
  }
}

I hope it can help you...

Tags: