[英]How can I center the error text of a TextFormField in Flutter?
I have a TextFormField that displays an error message when invalid.我有一个 TextFormField 在无效时显示错误消息。 It works great, but I'd like the error text to be centered.
它工作得很好,但我希望错误文本居中。
Container(
child: TextFormField(
validator: (val) => val.isEmpty ? 'Enter a Username' : null,
onChanged: (val) {setState(() => username = val);},
textAlign: TextAlign.center,
decoration: InputDecoration(
hintText: 'Pick Your Username',
errorStyle: // is it possible to center the errorText?
),
),
),
Using the errorStyle property, I can change the color, weight, size, etc. However, I haven't been able to figure out how to get the little red text that appears when the TextFormField is invalid to center.使用 errorStyle 属性,我可以更改颜色、重量、大小等。但是,我无法弄清楚如何让 TextFormField 无效时出现的红色小文本居中。
Thanks in advance for any advice!提前感谢您的任何建议!
The default style of the error for Material TextField is displayed on the lower left portion of the Widget. Material TextField 的默认错误样式显示在 Widget 的左下部分。 If you'd like to modify how the error is displayed, you can create a Widget to display the error message.
如果您想修改错误的显示方式,可以创建一个 Widget 来显示错误消息。
Here's a sample.这是一个示例。
import 'package:flutter/material.dart';
class SampleTextField extends StatefulWidget {
const SampleTextField({Key? key, required this.title}) : super(key: key);
final String title;
@override
State<SampleTextField> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<SampleTextField> {
final _formKey = GlobalKey<FormState>();
bool textFieldError = false;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: StatefulBuilder(
builder:
(BuildContext context, void Function(void Function()) setState) {
return Center(
child: Form(
key: _formKey,
child: Column(
children: [
TextFormField(
onFieldSubmitted: (String text) {
_formKey.currentState!.validate();
},
validator: (String? text) {
// Update textFieldError to determine if an error should be displayed
setState(() {
textFieldError = text == null || text.isEmpty;
debugPrint('Error: $textFieldError');
});
// Return a null on validator to not display the default error from the TextField
return null;
},
decoration: const InputDecoration(
hintText: 'Hint Text',
border: OutlineInputBorder(),
),
),
textFieldError
? const Text('Error Text',
style: TextStyle(color: Colors.red),
)
: const SizedBox()
],
),
),
);
},
),
);
}
}
Return null
on TextFormField.validator()
so the default error style won't be displayed.在
TextFormField.validator()
上返回null
,因此不会显示默认错误样式。 You can then use a StatefulBuilder so the entire Screen won't be rebuilt when setState()
was called.然后,您可以使用 StatefulBuilder 以便在调用
setState()
时不会重建整个屏幕。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.