我正在尝试创建一个 TextFormField,在验证错误的情况下,只有红色边框,而这种情况正在发生。但是,有一个奇怪的行为,当发生字段验证错误时,字段会向上移动。
我相信这是由我添加的“contentPadding”属性引起的,没有它,字段不会移动,但它最终会调整其高度,我不希望这种情况发生,我希望一切都保持固定它们的大小和位置,只有红色边框以防错误。
这是我的 TextFormField 的代码:
import 'package:beatscore/app/utils/beatscore_colors.dart';
import 'package:beatscore/main.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
// ignore: must_be_immutable
class CustomTextField extends StatelessWidget {
CustomTextField(
{super.key,
required this.onMutted,
this.placeholder,
this.protected = false,
this.prefixIcon,
this.suffixIcon,
this.suffixAction,
this.inputFormatters,
this.validator,
this.controller,
this.textInputType,
this.errorText});
Icon? prefixIcon;
Icon? suffixIcon;
bool protected;
Function()? suffixAction;
Function onMutted;
String? placeholder;
TextEditingController? controller;
String? Function(String)? validator;
List<TextInputFormatter>? inputFormatters;
TextInputType? textInputType;
String? errorText;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(
horizontal: 16,
vertical: 8,
),
child: SizedBox(
width: 310,
child: TextFormField(
keyboardType: textInputType,
autovalidateMode: AutovalidateMode.onUserInteraction,
validator: validator == null ? null : (value) => validator!(value!),
inputFormatters: inputFormatters,
onChanged: (value) => onMutted(value),
cursorColor: const Color.fromARGB(255, 0, 0, 0),
style: const TextStyle(
fontSize: 16,
color: Color.fromRGBO(30, 30, 30, 0.6),
height: 1.6),
obscureText: protected,
controller: controller,
decoration: InputDecoration(
errorBorder: const OutlineInputBorder(
borderSide: BorderSide(color: BeatscoreColors.ligthErrorRed),
),
contentPadding: const EdgeInsets.symmetric(
horizontal: 12.5,
vertical: 12.5,
),
errorText: errorText,
hintText: placeholder,
prefixIcon: prefixIcon,
suffixIcon: suffixIcon != null
? IconButton(
icon: suffixIcon!,
onPressed: suffixAction,
)
: null,
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
borderSide: const BorderSide(
width: 0,
style: BorderStyle.none,
)),
filled: true,
fillColor: Colors.white,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
borderSide: const BorderSide(
width: 0,
style: BorderStyle.none,
),
),
),
),
),
);
}
}
GIF 显示正在发生的事情:
发生的情况是,您很可能从
validator
回调中返回一个空(或包含其他空白)字符串。然后,Flutter 绘制此 errorText
(如果文本为空,则仅绘制文本的支柱),并在文本和输入本身之间添加一个额外的间隙。
import 'package:flutter/material.dart';
void main() {
runApp(
MaterialApp(
home: Scaffold(
body: Column(
children: const [
TextField(
decoration: InputDecoration(errorText: 'Some error'),
),
TextField(
decoration: InputDecoration(errorText: ''),
),
TextField(),
]
.map(
(w) => Container(
decoration: BoxDecoration(
color: Colors.blue.withOpacity(0.1),
border: Border.all(color: Colors.blue),
),
margin: const EdgeInsets.all(32),
child: w,
),
)
.toList(),
),
),
),
);
}