答案 0 :(得分:0)
TextEditingController 的值会重置,因为您正在build方法中对其进行实例化,因此每次重新构建树时,都会再次实例化控制器。 因此,要解决此问题,只需在build方法之外声明您的控制器:
class _AuthState extends State<Auth> {
final emailController = TextEditingController(); //right here
final passwordController = TextEditingController();
要将光标移动到另一个字段,您将需要使用 FocusNode 和用户按下Enter键时调用的某些函数,例如onEditingComplete:
class _AuthState extends State<Auth> {
final emailController = TextEditingController();
final passwordController = TextEditingController();
final emailNode = FocusNode();
final passNode = FocusNode(); //the nodes to request focus and move the cursor
接收func和focusNode作为参数,而且,您无需在此处使用有状态的小部件:
class FieldWithIcon extends StatelessWidget {
final String buttonText;
final IconData buttonIcon;
final FocusNode node;
final VoidCallback onEditingComplete;
final TextEditingController controller;
final bool obscureText;
FieldWithIcon({
this.buttonText,
this.buttonIcon,
this.controller,
this.obscureText,
this.node,
this.onEditingComplete,
});
@override
Widget build(BuildContext context) {
return Container(
decoration: BoxDecoration(
border: Border.all(color: Color(0xFFBC7C7C7), width: 2),
borderRadius: BorderRadius.circular(50)),
child: Row(
children: <Widget>[
Container(
width: 60,
child: Icon(
buttonIcon,
size: 20,
color: Color(0xFFBB9B9B9),
),
),
Expanded(
child: TextFormField(
onEditingComplete: onEditingComplete, //the func/callback
focusNode: node, //the node to request focus
controller: controller,
autocorrect: false,
decoration: InputDecoration(
border: InputBorder.none,
hintText: buttonText,
hintStyle: GoogleFonts.titilliumWeb(),
),
maxLines: 1,
obscureText: obscureText,
validator: (input) {
if (input.isEmpty) {
return "Invalid";
} else {
return null;
}
},
),
)
],
),
);
}
}
现在将函数/回调和焦点节点传递到您的字段:
FieldWithIcon(
buttonText: "Input your Email",
buttonIcon: Icons.email,
controller: emailController,
node: emailNode,
onEditingComplete: () => passNode.requestFocus(), //requesting focus of the next field
obscureText: false,
),
SizedBox(height: 20),
FieldWithIcon(
buttonText: "Input your Password",
buttonIcon: Icons.vpn_key,
controller: passwordController,
node: passNode,
onEditingComplete: () => passNode.unfocus(), //unfocus the field when enter is pressed
obscureText: true,
),