我需要有关此功能的帮助。当我在文本字段中输入文本时,我需要您在我输入另一个文本字段时验证该文本。
这是我的代码
class _ProfileState extends State<Profile> {
bool _hasInputError = false;
var idNumber = '';
var nombreUser = "";
FocusNode focusNode;
void initState() {
super.initState();
focusNode = new FocusNode();
focusNode.addListener(() {
if (!focusNode.hasFocus) {
setState(() {
_hasInputError = idNumber.length < 3;
});
}
});
}
@override
Widget build(BuildContext context) {
final nombreUserField = TextField(
focusNode: _focusNode,
onChanged: (String text) {
nombreUser = text;
},
);
final idNumberElement = TextField(
focusNode: _focusNode,
decoration: InputDecoration(
errorText: _hasInputError ? "Id is too short" : null,
counterText: "",
),
onChanged: (String tex) {
idNumber = tex;
},
);
return WillPopScope(
child: Scaffold(
body: Listener(
onPointerUp: (e) {
FocusScope.of(context).requestFocus(FocusNode());
},
child: SingleChildScrollView(
child: Container(child: Column(
children: <Widget>[
SizedBox(
height: 10,
),
idNumberElement,
SizedBox(
height: 20,
),
nombreUserField,
],
),
),
),
),
));
}
}
我试图让验证出现在 onEditingComplete 中,但它不起作用。我尝试了这个答案,但它不起作用。
最佳答案
initState
应该在 build
函数之外。您已在 build
initState
FocusNode focusNode;
void initState() {
super.initState();
focusNode = new FocusNode();
focusNode.addListener(() {
if (!focusNode.hasFocus) {
setState(() {
_hasInputError = idNumber.length < 3;
});
}
});
}
@override
Widget build(BuildContext context){
..
}
你的代码
@override
Widget build(BuildContext context) {
var _focusNode = FocusNode();
void initState() {
super.initState();
_focusNode.addListener(() {
if (!_focusNode.hasFocus) {
if (idNumber.length < 3) {
"Id is too short";
}
}
});
}
..
}
您还应该使用 setState
来指示您已经更改了 _hasInputError
的值,以便框架可以安排构建并且可以更新此子树的用户界面反射(reflect)新状态
您在两个 TextField
中都有相同的 FocusNode
对象。从 nombreUserField
中删除 _focusNode
。 FocusNode
用于标识 Flutter 焦点树中的特定 TextField
。每个 TextField
都应该有一个不同的 FocusNode。
关于flutter - 当我关注另一个 textField 时验证 textField,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58863269/