Flutter Tutorial: How to use a TextField

 In this tutorial, we will learn how to use a TextField widget in Flutter Application using an example.

TextField is used to get text input from users. The default behavior of TextField is that, when you press on it, it gets focus, and a keyboard slides from the bottom of the screen. When you enter text using a keyboard, the string is displayed in the TextField.

Introduction to TextField

A TextField widget allows the collection of information from the user. The code for a basic TextField is as simple as:


This creates a basic TextField:


Retrieving information from a TextField

Since TextFields does not have an ID like in Android, text cannot be retrieved upon demand and must instead be stored in a variable on change or use a controller.

The easiest way to do this is to use the onChanged method and store the current value in a simple variable. Here is the sample code for it:

String value = "";
  onChanged: (text) {
    value = text;

2. The second way to do this is to use a TextEditingController. The controller is attached to TextField and lets us listen and control the text of TextField as well.

TextEditingController controller = TextEditingController();
  controller: controller,
The Main.dart

import 'package:flutter/material.dart'; void main() { runApp(MyApp()); } class MyApp extends StatefulWidget { @override _MyAppState createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { TextEditingController nameController = TextEditingController(); String email = ''; @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: Text('Flutter - Nityzeros.com'), ), body: Center(child: Column(children: <Widget>[ Container( margin: EdgeInsets.all(20), child: TextField( controller: nameController, decoration: InputDecoration( border: OutlineInputBorder(), labelText: 'Email', ), onChanged: (text) { setState(() { email = text; //you can access nameController in its scope to get // the value of text entered as shown below //fullName = nameController.text; }); }, )), Container( margin: EdgeInsets.all(20), child: Text(email), ) ]))), ); } }

Hey I'm Venkat
Developer, Blogger, Thinker and Data scientist. nintyzeros [at] gmail.com I love the Data and Problem - An Indian Lives in US .If you have any question do reach me out via below social media

This Is The Newest Post