ashkan117
ashkan117

Reputation: 1098

TextFormField Flutter not changing appropriately

I have a form that I would like to be updated programatically from another widget is pressed. To test this I made the label text update with the same text and this worked as expected.

For some reason the inital value is not updated even though in debugging it does show the string to be the correct value. I added a controller to handle the text but i still don't understand why the initial value was not working the way I thought it would.

new TextFormField(
          key: _orderAddEditOrderFormKey,
          decoration: InputDecoration(
              labelText: order.order == null ? 'Order' : order.order),
          initialValue: order.order == null ? "" : order.order,
        ),

setState(() {
            isBuildOrderUsed = true;
            if (this.order == null) {
              this.order = new Order(order: order);
            } else {
              this.order.order = order;
            }
          });

Upvotes: 6

Views: 5250

Answers (2)

LiveRock
LiveRock

Reputation: 1043

The only way to change the initialtext of a TextFormField is to use a TextEditingController() like so:

final _textEditingController = TextEditingController();

_textEditingController.addListener(_textEditingControllerListener);

void _textEditingControllerListener() {
    _textEditingController.text = newValue;
}

Upvotes: 1

diegoveloper
diegoveloper

Reputation: 103551

That is because the initialValue is set in the initState with theTextEditingController so you can not update that value, it is just the 'initial value'.

Check the source code of the TextFormField :

     @override
      void initState() {
        super.initState();
        if (widget.controller == null) {
          _controller = new TextEditingController(text: widget.initialValue);
        } else {
          widget.controller.addListener(_handleControllerChanged);
        }
      }

Upvotes: 7

Related Questions