Flutter: How to supply an initial value to a TextFormField

If you need to supply an initial value to a Flutter TextFormField (and possibly a TextField), the initialValue parameter may not do what you expect it to do. (More on this in the Discussion.) Instead, I just used this technique to populate the initial value for a TextFormField when using 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 initial text field value to the controller, like this:

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

Also, note that while I populate the TextEditingController objects in my constructor, they can also be populated in the initState method:

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

Discussion: The initialValue parameter

I initially thought the initialValue parameter of the TextFormField could be used for this purpose, but when I tried to use it, it throws an error message that starts like this:

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 solution to this problem is found in the Flutter TextFormField class documentation:

“If a controller is not specified, initialValue can be used to give the automatically generated controller an initial value.”

So, if you’re using a controller as I am, using initialValue will not work, and in fact throws the error shown. So either:

  • Use a TextEditingController, and use the solution shown
  • Don’t use a TextEditingController, and supply the initialValue like this:
TextFormField(
    initialValue: 'Hello, world',
    ...
),

Summary

If you need to populate the initial value in a Flutter TextFormField (and possibly a TextField), I hope this example is helpful.