我想在TextField
中实现像Flutter
验证的Android。
我尝试了TextField
的Flutter
文档和InputDecoration
有errorText
的属性但是在textfield
的底部显示错误。我想在Flutter中实现类似下面的东西
您可以在TextFormField
中使用Tooltip
和自定义Stack
来实现此效果。在decoration
的TextFormField
属性中,您可以使用suffixIcon
类的InputDecoration
属性来传递错误图标。
并且您可以使用bool
变量在发生验证错误时显示/隐藏工具提示消息。
TextFormField
的示例代码:
TextFormField(
decoration: InputDecoration(
//Set the different border properties for a custom design
suffixIcon: IconButton(
icon: Icon(Icons.error, color: Colors.red),
onPressed: () {
setState(() {
showTooltip = !showTooltip; //Toggles the tooltip
});
},
),
),
validator: (String value) {
if(value.isEmpty) {
setState(() {
showTooltip = true; //Toggles the tooltip
});
return "";
}
}
);
您可以使用Stack
将上述代码与自定义工具提示窗口小部件代码一起打包,以实现错误工具提示效果。
下面是一个快速工作的例子。您可以设计自己的自定义工具提示窗口小部件并在代码中使用它。
例:
class LoginAlternate extends StatefulWidget {
@override
_LoginAlternateState createState() => _LoginAlternateState();
}
class _LoginAlternateState extends State<LoginAlternate> {
GlobalKey<FormState> _formKey = GlobalKey();
bool showTooltip = false;
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.blueGrey,
body: Container(
padding: EdgeInsets.symmetric(
horizontal: 100,
vertical: 100
),
child: Form(
key: _formKey,
child: Column(
children: <Widget>[
Stack(
alignment: Alignment.topRight,
overflow: Overflow.visible,
children: <Widget>[
TextFormField(
decoration: InputDecoration(
filled: true,
fillColor: Colors.white,
border: OutlineInputBorder(
borderSide: BorderSide.none
),
suffixIcon: IconButton(
icon: Icon(Icons.error, color: Colors.red,),
onPressed: () {
setState(() {
showTooltip = !showTooltip;
});
},
),
hintText: "Password"
),
validator: (value) {
if(value.isEmpty) {
setState(() {
showTooltip = true;
});
return "";
}
},
),
Positioned(
top: 50,
right: 10,
//You can use your own custom tooltip widget over here in place of below Container
child: showTooltip
? Container(
width: 250,
height: 50,
decoration: BoxDecoration(
color: Colors.white,
border: Border.all( color: Colors.red, width: 2.0 ),
borderRadius: BorderRadius.circular(10)
),
padding: EdgeInsets.symmetric(horizontal: 10),
child: Center(
child: Text(
"Your passwords must match and be 6 characters long.",
),
),
) : Container(),
)
],
),
RaisedButton(
child: Text("Validate"),
onPressed: () {
_formKey.currentState.validate();
},
),
],
),
),
),
);
}
}
您可以使用叠加小部件自定义此类错误。可以使用overlay小部件显示错误,并且可以使用TextField的inputDecoration更改错误图标。
以下是了解叠加小部件 - https://medium.com/saugo360/https-medium-com-saugo360-flutter-using-overlay-to-display-floating-widgets-2e6d0e8decb9的链接