我想在调用onSubmit方法时更改TextField的修饰,在setState中,当我调用返回InputDecoration的函数时,它不会改变TextField的修饰。
实际上,如果没有通过更改TextField的装饰来警告他们,我想检查用户是否正确填写了TextField。
class CustomTextField extends StatefulWidget {
final TextEditingController controller;
final IconData icon;
final String textLabel;
final TextInputType textInputType;
CustomTextField(
this.controller, this.icon, this.textLabel, this.textInputType);
@override
_CustomTextFieldState createState() => _CustomTextFieldState();
}
class _CustomTextFieldState extends State<CustomTextField> {
InputDecoration inputDecoration;
double a = 0;
bool b = true;
@override
Widget build(BuildContext context) {
inputDecoration = noramlInputDecoration(context, widget.textLabel, Icon(widget.icon));
return Container(
margin: EdgeInsets.only(top: responsiveHeight(context, 0.8)),
child: TextField(
onSubmitted: (mahdi) {
print('adfaf');
setState(() {
inputDecoration = noramlInputDecoration(
context, widget.textLabel, Icon(widget.icon));
});
a++;
print(a);
},
decoration: inputDecoration,
onTap: () {},
toolbarOptions: ToolbarOptions(
paste: true,
copy: true,
cut: true,
selectAll: true,
),
cursorWidth: 2,
style: TextStyle(
fontSize: responsiveWidthGivenWidth(
responsiveWidth(context, 81.6) / 10, 53.3),
height: 0.5),
controller: widget.controller,
maxLines: 1,
obscureText: b,
showCursor: true,
textAlign: TextAlign.end,
textDirection: TextDirection.ltr,
keyboardType: widget.textInputType,
inputFormatters: [],
),
);
}
}
这是我返回输入装饰的两种方法。
InputDecoration errorInputDecoration(
BuildContext context, IconData icon, String hintText, String errorText) {
InputDecoration inputDecoration;
inputDecoration = InputDecoration(
suffixIcon: Padding(
padding: EdgeInsets.only(
right: responsiveWidthGivenWidth(responsiveWidth(context, 81.6), 5.2),
),
child: Icon(
icon,
color: blue,
),
),
hintText: hintText,
errorText: errorText,
errorMaxLines: 2,
errorStyle: TextStyle(
color: Colors.red,
),
errorBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(50),
borderSide: BorderSide(
color: Colors.red,
width: 2,
),
),
focusedErrorBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(50),
borderSide: BorderSide(
color: Colors.red,
width: 4,
),
),
);
return inputDecoration;
}
InputDecoration noramlInputDecoration(
BuildContext context, String hintText, Icon icon) {
return InputDecoration(
suffixIcon: Padding(
padding: EdgeInsets.only(
right: responsiveWidthGivenWidth(responsiveWidth(context, 81.6), 5.2),
),
child: Icon(
icon.icon,
color: blue,
),
),
hintText: hintText,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(50),
borderSide: BorderSide(
color: Colors.blue[200],
width: 2,
),
),
);
}
正如@Ryosuke在问题的评论中所说,我不应该在构建方法中使用 setState((,因为每次调用它时都会卡在循环中并且总是调用 build(( 方法。