Search code examples
controllerfluttertextfielddefault-valuestream-builder

TextField with initial value inside StreamBuilder


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

Solution

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