在TextField
模式之后,我在StreamBuilder
的帮助下呈现了BLoC
,带有接收器和流。
Widget field(SignUpBloc signUpBloc) {
return StreamBuilder(
stream: signUpBloc.outFirstName,
builder: (context, snapshot) {
return TextField(
style: TextStyle(fontSize: 15.0),
onChanged: signUpBloc.inFirstName,
decoration: InputDecoration(
errorStyle: TextStyle(fontSize: 15.0),
errorText: snapshot.error
),
);
},
);
}
我的问题是如何设置初始值?我尝试使用StreamBuilder
的{{1}}属性,但是initialData
中没有文本。
答案 0 :(得分:2)
当您需要传递初始值时,您将必须具有TextEditingController。使用value.copyWith策略无需处理游标,并且为了使小部件更整洁,您可以将文本控制器作为参数传递。
// Stream widget
Widget field(SignUpBloc signUpBloc, TextEditingController _txtController) {
return StreamBuilder(
stream: signUpBloc.outFirstName,
builder: (context, snapshot) {
_txtController.value =
_txtController.value.copyWith(text: snapshot.data);
return TextField(
controller: _txtController,
onChanged: signUpBloc.inFirstName;
decoration: InputDecoration(
errorStyle: TextStyle(fontSize: 15.0),
errorText: snapshot.error
),
});
}
答案 1 :(得分:1)
TextEditingController _controller = TextEditingController(); // make a controller,
Widget field(SignUpBloc signUpBloc) {
return StreamBuilder(
stream: signUpBloc.outFirstName,
initialData: YourData, // provide initial data
builder: (context, snapshot) {
_controller.value = TextEditingValue(text: "${snapshot.data}"); // assign value to controller this way
return TextField(
controller: _controller,
style: TextStyle(fontSize: 15.0),
onChanged: signUpBloc.inFirstName,
decoration: InputDecoration(
errorStyle: TextStyle(fontSize: 15.0),
errorText: snapshot.error
),
);
},
);
}
编辑:要将光标放在行尾,可以使用
var cursorPos = _controller.selection;
if (cursorPos.start > _controller.text.length) {
cursorPos = TextSelection.fromPosition(TextPosition(offset: _controller.text.length));
}
_controller.selection = cursorPos;