There are two primary ways to supply an initial value to a text field in Flutter, depending on the widget you are using:
-
Using a
TextEditingController(Recommended for state management)1 -
Using the
initialValueproperty (For stateless fields)2
1. Using a TextEditingController 📝
The most common and flexible way is to use a TextEditingController and set its initial text property.3 This is the recommended approach because the controller is essential for managing and reacting to the text field’s state (getting/setting text, controlling selection, etc.).
Implementation Steps:
-
Create a Controller: Declare and initialize a
TextEditingControllerinstance, setting the initial text in its constructor.4 This is typically done within theStateclass’sinitState()method or as a class member.final myController = TextEditingController(text: 'Initial Text Here'); -
Assign the Controller: Pass the controller to the
TextFieldorTextFormFieldwidget’scontrollerproperty.TextField( controller: myController, // ... other properties ) -
Dispose (Crucial): Remember to dispose of the controller in the
dispose()method of yourStateto free up resources.@override void dispose() { myController.dispose(); super.dispose(); }
2. Using the initialValue Property ✨
The initialValue property is available only on TextFormField (often used within a Form widget).5 It’s a simpler method if you only need to set an initial value and don’t immediately need programmatic control over the text field content (like programmatically changing the text or reading it before form submission).
Implementation Steps:
-
Set
initialValue: Directly set theinitialValueproperty of theTextFormField.TextFormField( initialValue: 'Simple Initial Value', // ... other properties (like validator, onSaved) )
Important Note on initialValue:
-
Incompatibility: You cannot use both
controllerandinitialValuesimultaneously. If both are provided, thecontrollertakes precedence, andinitialValuewill be ignored, often resulting in an assertion error during development. -
If you later need to change the text programmatically or read the text outside of the
Form‘s lifecycle (like in anonChangedcallback), you will have to create and assign aTextEditingController, making theinitialValueirrelevant. This is the case with different State Management Solutions.
