close

how do i supply an initial value to a text field?

In the event that you need to supply an underlying incentive to a Flutter TextFormField (and perhaps a TextField), the initialValue boundary may not do what you anticipate that it should do. (More on this in the Discussion.) Instead, I just utilized this procedure to populate the underlying incentive for a TextFormField when utilizing it with a TextEditingController:

class EditQuoteFormState extends State<EditQuoteForm> {

  // STEP 1
  TextEditingController _quoteController;
  TextEditingController _authorController;

  Quote _quote;

  EditQuoteFormState(this._quote) {
    /// STEP 2
    /// this code populates the `text` field, which is used later
    /// by the controllers
    _quoteController = TextEditingController(text: _quote.quote);
    _authorController = TextEditingController(text: _quote.author);
  }
  
  // later ...
  
  @override
  Widget build(BuildContext context) {

      // STEP 3
      TextFormField(
        controller: _quoteController,
        ...
      ),
      TextFormField(
        controller: _authorController,
        ...

The key here is to pass the underlying content field an incentive to the regulator, similar to this:

_myController = TextEditingController(text: 'The initial value');

Additionally, note that while I populate the TextEditingController objects in my constructor, they can likewise be populated in the initState strategy:

@override
void initState() {
    super.initState();
    _quoteController = TextEditingController(text: "Hello, world");
    _authorController = TextEditingController(text: "Kernighan and Ritchie");
}

Discussion: The initialValue parameter

I at first idea the initialValue boundary of the TextFormField could be utilized for this reason, yet when I attempted to utilize it, it tosses a blunder message that starts this way:

flutter: ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞══
flutter: The following assertion was thrown building Builder(dirty):
flutter: 'package:flutter/src/material/text_form_field.dart': Failed assertion: line 117 pos 15:
flutter: 'initialValue == null || controller == null': is not true.

Part of the answer for this issue is found in the Flutter TextFormField class documentation:

“On the off chance that a regulator isn’t determined, initialValue can be utilized to give the naturally created regulator an underlying worth.”

In this way, in case you’re utilizing a regulator as I am, utilizing initialValue won’t work, and truth be told tosses the blunder appeared. So by the same token:

  • Utilize a TextEditingController, and utilize the arrangement appeared
  • Try not to utilize a TextEditingController, and supply the initialValue like this:
TextFormField(
    initialValue: 'Hello, world',
    ...
),

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you? Thank You.

Also Read

Leave a Comment