Flutter – ‘initialValue == null || controller == null’: is not true. error

Posted by

The error you’re encountering in Flutter, 'initialValue == null || controller == null': is not true, typically occurs when you’re using a TextFormField or TextField widget and either the controller or initialValue parameter is null when it shouldn’t be.

Here’s what the error means:

  • TextFormField or TextField widget has a controller property which allows you to manage the value of the text field.
  • initialValue is used to initialize the value in a form field.
  • The error message indicates that either initialValue is null or controller is null when both should be provided (or at least one of them).

Sulotion

Check Controller Initialization

If you’re using a TextEditingController, ensure that it is initialized before you use it in the widget. For example:

final TextEditingController _controller = TextEditingController();

@override
void dispose() {
  _controller.dispose(); // Don't forget to dispose of the controller!
  super.dispose();
}

Then, pass it to the controller property of TextFormField or TextField:

TextFormField(
  controller: _controller, // Pass initialized controller here
  decoration: InputDecoration(labelText: 'Enter text'),
)

Ensure initialValue is Provided

If you’re using the initialValue property, make sure that it is not null or, if it could be null, you handle it properly. For example, you can provide a default value if initialValue might be null:

TextFormField(
  initialValue: initialValue ?? '',  // Provide default empty string if null
  decoration: InputDecoration(labelText: 'Enter text'),
)

Use Either controller or initialValue, Not Both

If you are using a TextEditingController, you should not use initialValue at the same time, because they both serve similar purposes.

If you’re using a controller, do not use initialValue:

TextFormField(
  controller: _controller,  // Only use controller, not initialValue
  decoration: InputDecoration(labelText: 'Enter text'),
)

If you’re using initialValue, you can omit the controller:

TextFormField(
  initialValue: 'Default Text',  // Use initialValue, not controller
  decoration: InputDecoration(labelText: 'Enter text'),
)

Check Your Form Widgets

If you’re using the widget within a Form and the error occurs there, ensure that your FormField has either controller or initialValue set properly:

Form(
  child: TextFormField(
    controller: _controller, // or initialValue, but not both
    decoration: InputDecoration(labelText: 'Enter text'),
  ),
)

Leave a Reply

Your email address will not be published. Required fields are marked *

0
Would love your thoughts, please comment.x
()
x