How to supply an Initialvalue to TextField Widget in Flutter?

· 3 min read
Supply Initial Values to TextField Widget
Supply Initial Values to TextField Widget

TextField Widget in Mobile Application is used to get data from users and store that data into the database. You may consider a case while editing a data user want that data back into TextField Widget.  In this article, we will be learning how to supply an Initialvalue to TextField Widget.

Are you ready for it? Let’s start with supply an Initialvalue to TextField Widget.

To set Initial Values to TextField Widget our code snippet will look like below:

TextField(
  controller: TextEditingController()..text = 'Your initial value',
  onChanged: (text) => {},
)

If you are using TextEditingController then set the text to it, like below:

TextEditingController _controller = new TextEditingController();


_controller.text = 'your initial text';

final your_text_name = TextFormField(
      controller: _controller,
    );

To clear the text you can use _controller.clear() method.

If you are not using any TextEditingController then you can directly use initialValue.

You can use a TextFormField instead of TextField Widget and use the initialValue property.

The code snippet will look like below:

TextFormField(initialValue: "Hello I am Initial Value")

When you are using TextEditingController users can try a code snippet like below as well.

TextField(
   controller: TextEditingController(text: "Initial Text here"),
)

When a user wants to handle multiple TextInputs they can also create a function that takes an initial value and returns a TextEditingController like this:

initialValue(val) {
  return TextEditingController(text: val);
}

Then, set this function as the controller for the TextInput and supply its initial value there like this:

controller: initialValue('Some initial value here....')

User can also specify the text into initState() like below:

@override
  void initState() {
    super.initState();
    controller.text = "Your Text";
    }

Key Notes :

Hint Text is not an initial value. When the user types something it would go away. Initial Text is like pre-write something for the user.

Conclusion:

In this article, We have been through How to Supply an Initialvalue to TextField Widget in Flutter? 

Keep Learning !!! Keep Fluttering!!!

FlutterAgency.com is our portal Platform dedicated to Flutter Technology and Flutter Developers. The portal is full of cool resources from Flutter like Flutter Widget Guide, Flutter Projects, Code libs and etc.

FlutterAgency.com is one of the most popular online portals dedicated to Flutter Technology and daily thousands of unique visitors come to this portal to enhance their knowledge of Flutter.

Leave a Reply