TextField with initial value inside StreamBuilder

8,672

Solution 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 .

Solution 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,
      );
    });

Solution 3

To have your cursor to the end of your text, when you edit your text controller, think about to also edit your selection controller like so :

controller.text = newText;
controller.selection = controller.selection.copyWith(baseOffset: newText.length, extentOffset: newText.length);

Hope it helped !

Share:
8,672
Vinicius Sossella
Author by

Vinicius Sossella

Updated on December 08, 2022

Comments

  • Vinicius Sossella
    Vinicius Sossella over 1 year

    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),
            ),
      ),