我需要有关此功能的帮助。当我在文本字段中输入文本时,我需要您在输入另一个文本字段时验证该文本。
这是我的代码
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,
],
),
),
),
),
));
}
}
Run Code Online (Sandbox Code Playgroud)
我试图让验证出现在 onEditingComplete 中,但它不起作用。我尝试这个答案,但它不起作用。
initState应该在build功能之外。你已经initState在里面声明了build
FocusNode focusNode;\n void initState() {\n super.initState();\n focusNode = new FocusNode();\n focusNode.addListener(() {\n if (!focusNode.hasFocus) {\n setState(() {\n _hasInputError = idNumber.length < 3;\n });\n }\n });\n }\n @override\n Widget build(BuildContext context){\n ..\n }\nRun Code Online (Sandbox Code Playgroud)\n\n你的代码
\n\n@override\n Widget build(BuildContext context) {\n var _focusNode = FocusNode();\nvoid initState() {\n super.initState();\n _focusNode.addListener(() {\n if (!_focusNode.hasFocus) {\n if (idNumber.length < 3) {\n "Id is too short";\n }\n }\n });\n}\n..\n}\nRun Code Online (Sandbox Code Playgroud)\n\n您还应该使用setState来指示您已更改 的值,_hasInputError以便框架可以安排构建,并且可以更新此子树的用户界面以反映新状态
你FocusNode在两个都有相同的对象TextField。_focusNode从 中删除nombreUserField. FocusNode用于识别TextFieldFlutter\xe2\x80\x99s 焦点树中的特定焦点。每个都TextField应该有不同的 FocusNode。
| 归档时间: |
|
| 查看次数: |
4313 次 |
| 最近记录: |