我试图达到的目的是,一旦输入了多个字符,就可以自动验证TextInputField。
这是我的initState(简体):
@override
void initState() {
autoValidateList.addAll([
_autoValidateEmail,
_autoValidateCompanyName,
_autoValidatePhoneNo,
_autoValidateName,
_autoValidateSurname
]);
textEditingControllersList.addAll([
_emailController,
_companyNameController,
_phoneNoController,
_nameController,
_surnameController
]);
for (int i = 0; i < textEditingControllersList.length; i++) {
TextEditingController controller = textEditingControllersList[i];
controller.addListener(() => () {
print(
'Listener entered. companyName? ${controller == _companyNameController}');
if (controller.text.length > 0) {
print('=> true');
setState(() => autoValidateList[i] = true);
} else {
print('=> false');
setState(() => autoValidateList[i] = false);
}
});
}
_emailController.text = widget.loginData.email;
super.initState();
}
例如,如果我不在循环中添加侦听器,则:
_emailController.addListener(() => setState(() {
if (_emailController.text.length > 0) {
_autoValidateEmail = true;
} else {
_autoValidateEmail = false;
}
}));
它工作正常。
没有任何打印语句被执行。我在这里想念什么?
答案 0 :(得分:1)
这里有一个非常隐蔽的错误。请注意,在您的addListener
中,您传递了一个返回函数的函数。您想要执行的是正在返回的函数,但实际上您正在执行要传递的函数。
使用更清晰的语法,您正在执行以下操作:
controller.addListener(() {
return () {
// Your code
};
});
所以,正在发生的事情是:
controller.addListener(() {
print('This is going to be executed');
return () {
print('This is NOT going to be executed. Your code used to be here.');
};
});
代替:
controller.addListener(() => () {
...
});
您应该这样做:
controller.addListener(() {
...
});
这也不相关,但是您应该在super
的开头而不是结尾处调用initState
。