How do you change the value inside of a textfield flutter?

后端 未结 10 1688
忘掉有多难
忘掉有多难 2020-12-06 08:49

I have a TextEditingController where if a user clicks a button it fills in with information. I can\'t seem to figure out how to change the text inside of a

10条回答
  •  鱼传尺愫
    2020-12-06 09:24

    The problem with just setting

    _controller.text = "New value";
    

    is that the cursor will be repositioned to the beginning (in material's TextField). Using

    _controller.text = "Hello";
    _controller.selection = TextSelection.fromPosition(
        TextPosition(offset: _controller.text.length),
    );
    setState(() {});
    

    is not efficient since it rebuilds the widget more than it's necessary (when setting the text property and when calling setState).

    --

    I believe the best way is to combine everything into one simple command:

    final _newValue = "New value";
    _controller.value = TextEditingValue(
          text: _newValue,
          selection: TextSelection.fromPosition(
            TextPosition(offset: _newValue.length),
          ),
        );
    

    It works properly for both Material and Cupertino Textfields.

提交回复
热议问题