问题
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