Skip to content
Related Articles

Related Articles

Retrieve Data From TextFields in Flutter
  • Difficulty Level : Expert
  • Last Updated : 14 Aug, 2020

In this article, we’ll learn how to retrieve data from TextFields. TextField() widget is the most common widget used in flutter apps to take user input. We’ll talk about two major methods used to extract text from TextField.

Using Variables:

The TextField widget has various callback properties through which we can extract text. Majorly, onChanged is used as it takes input on every change incurred in the TextField. This callback doesn’t work when TextField’s text is changed programmatically. Basically, this kind of change is initiated by the app itself.

Syntax:
TextField(
   onChanged: (value) {
       print("The value entered is : $value");
   }
)

Various other callbacks are also available for TextFields like onTap, onSubmitted, onEditingComplete.

  • onTap: It is called for each unique tap except for every second tap of double-tap. Internally, it builds a GestureDetector to handle this kind of event. You can use it whenever you want to trigger some property of TextField which is gesture-based.
  • onSubmitted: It is called whenever the user indicates that they are done with editing the text. Primarily, whenever the done button is pressed on the keyboard, it will be called and the data entered would be stored.
  • onEditingComplete: It is very similar to onSubmitted. The only difference is that it is called whenever the button in the bottom right corner of the keyboard is pressed. It might be ‘done’, ‘send’, ‘go’, or ‘search’.

Example:

Below is the example of onChanged in TextField. Here, we have used an anonymous function to receive a callback from onChanged. The value from callback is received in value, then we pass it to our variable title.



Dart




import "package:flutter/material.dart";
  
void main() => runApp(MyApp());
  
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Home(),
    );
  }
}
  
class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}
  
class _HomeState extends State<Home> {
  // var to store
  // onChanged callback
  String title;  
  String text = "No Value Entered";
  
  void _setText() {
    setState(() {
      text = title;
    });
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('GeeksforGeeks'),
        backgroundColor: Colors.green,
      ),
      body: Column(
        children: [
          Padding(
            padding: const EdgeInsets.all(15),
            child: TextField(
              decoration: InputDecoration(labelText: 'Title'),
                
              onChanged: (value) => title = value, 
                
            ),
          ),
          SizedBox(
            height: 8,
          ),
          RaisedButton(
            onPressed: _setText,
            child: Text('Submit'),
            elevation: 8,
          ),
          SizedBox(
            height: 20,
          ),
          Text(text),  
          // changes in text 
          // are shown here
        ],
      ),
    );
  }
}

Output

Using Controller:

Another way to retrieve text is by using the controller. It is a property that flutter provides with TextField. Below are the steps explaining the use of the controller.

  • First, create an object of the class TextEditingController().  It is the default class that is provided by flutter.
  • Connect the object created to the controller of the TextField.
  • Now, you may create a function to get the latest value.

It works almost the same way as onChanged. But, in certain scenarios, it is preferred to use controller as the retrieving process is managed by the flutter engine.

Example:

The below example, explains using the controller for retrieving values from TextField. Firstly, create an object of type TextEditingController. Then we assign this object to the controller property of TextField.

Dart




import "package:flutter/material.dart";
  
void main() => runApp(MyApp());
  
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Home(),
    );
  }
}
  
class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}
  
class _HomeState extends State<Home> {
  final titleController = TextEditingController();
  String text = "No Value Entered";
  
  void _setText() {
    setState(() {
      text = titleController.text;
    });
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('GeeksforGeeks'),
        backgroundColor: Colors.green,
      ),
      body: Column(
        children: [
          Padding(
            padding: const EdgeInsets.all(15),
            child: TextField(
              decoration: InputDecoration(labelText: 'Title'),
                
              controller: titleController,
                
            ),
          ),
          SizedBox(
            height: 8,
          ),
          RaisedButton(
            onPressed: _setText,
            child: Text('Submit'),
            elevation: 8,
          ),
          SizedBox(
            height: 20,
          ),
          Text(text),
        ],
      ),
    );
  }
}

Output

Both methods can be used for retrieving text, as the output of both are the same. Here, we had to re-run the build method to update text, hence we have used a stateful widget. If, in your program, you just want to store the value, a stateless widget can also be used.

My Personal Notes arrow_drop_up
Recommended Articles
Page :