Open In App

Retrieve Data From TextFields in Flutter

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.

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.




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.

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.




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.


Article Tags :