Open In App

Retrieve Data From TextFields in Flutter

Improve
Improve
Like Article
Like
Save
Share
Report

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(const MyApp());
 
class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
 
  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: Home(),
    );
  }
}
 
class Home extends StatefulWidget {
  const Home({Key? key}) : super(key: key);
 
  @override
  // ignore: library_private_types_in_public_api
  _HomeState createState() => _HomeState();
}
 
class _HomeState extends State<Home> {
// var to store
// onChanged callback
  late String title;
  String text = "No Value Entered";
 
  void _setText() {
    setState(() {
      text = title;
    });
  }
 
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('GeeksforGeeks'),
        backgroundColor: Colors.green,
      ),
      body: Column(
        children: [
          Padding(
            padding: const EdgeInsets.all(15),
            child: TextField(
              decoration: const InputDecoration(labelText: 'Title'),
              onChanged: (value) => title = value,
            ),
          ),
          const SizedBox(
            height: 8,
          ),
 
          ElevatedButton(
              onPressed: _setText,
              style: ButtonStyle(
                  elevation: MaterialStateProperty.all(8),
                  backgroundColor: MaterialStateProperty.all(Colors.green)),
              child: const Text('Submit')),
          // RaisedButton is deprecated and should not be used
          // Use ElevatedButton instead
           
          // RaisedButton(
          //     onPressed: _setText,
          //     child: Text('Submit'),
          //     elevation: 8,
          // ),
          const 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 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 the 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 the type TextEditingController. Then we assign this object to the controller property of TextField.

Dart




import "package:flutter/material.dart";
 
void main() => runApp(const MyApp());
 
class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
 
  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: Home(),
    );
  }
}
 
class Home extends StatefulWidget {
  const Home({Key? key}) : super(key: key);
 
  @override
  // ignore: library_private_types_in_public_api
  _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: const Text('GeeksforGeeks'),
        backgroundColor: Colors.green,
      ),
      body: Column(
        children: [
          Padding(
            padding: const EdgeInsets.all(15),
            child: TextField(
              decoration: const InputDecoration(labelText: 'Title'),
              controller: titleController,
            ),
          ),
          const SizedBox(
            height: 8,
          ),
          ElevatedButton(
              onPressed: _setText,
              style: ButtonStyle(
                  elevation: MaterialStateProperty.all(8),
                  backgroundColor: MaterialStateProperty.all(Colors.green)),
              child: const Text('Submit')),
 
          // RaisedButton is deprecated and should not be used
          // Use ElevatedButton instead
 
          // RaisedButton(
          //   onPressed: _setText,
          //   child: Text('Submit'),
          //   elevation: 8,
          // ),
          const SizedBox(
            height: 20,
          ),
          Text(text),
        ],
      ),
    );
  }
}


Output

Both methods can be used for retrieving text, as the output of both is 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.



Last Updated : 21 Jun, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads