TextField with initial value inside StreamBuilder

拈花ヽ惹草 提交于 2019-12-11 07:53:10

问题


We are creating an user's editing data page, so the textfield already comes filled with the user data and users can change and save it... The problem is that when I start to enter character into textfield, the cursor get lost, every character that I enter (from the device keyboard), the cursor goes to the first character... and if I remove the controller with my initial value, it works fine, but then I can not have my textfield filled with the users data.

Code sample:

child: StreamBuilder<String>(
    stream: _bloc.myStream,
    builder: (context, snap) => TextField(
          decoration: InputDecoration(
            hintText: 'example',
            labelText: 'Name',
            errorText: snap.error,
          ),
          onChanged: _bloc.updateMyStream,
          controller: TextEditingController(text: snap.data),
        ),
  ),

回答1:


Whenever you need to update your TextController text, to be able to edit it you need to fix your cursor position like this

textController.value = textController.value.copyWith(text:<NEW_VALUE>,);

replace NEW_VALUE by the new text .




回答2:


@XoXo here are the full code, But you can do it in your way.

TextEditingController _controller = TextEditingController();

return StreamBuilder<String>(
    stream: _bloc.myStream,
    builder: (context, snap) {
      _controller.value =
          _controller.value.copyWith(text: snap.data);

      return TextField(
        decoration: InputDecoration(
          hintText: 'ex: Centro',
          labelText: 'Bairro',
          errorText: snap.error,
        ),
        onChanged: _bloc.updateMyStream,
        controller: _controller,
      );
    });


来源:https://stackoverflow.com/questions/53682877/textfield-with-initial-value-inside-streambuilder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!