validation - 验证器到 TextField
问题描述
如何为 TextField 实现验证器。我知道 TextFormField 有一个验证器选项,但我需要 TextField 中的验证器。如果 TextField 值无效,我需要装饰它,就像 TextFormField 一样。
解决方案
你可以这样做:
class MyHomePage extends StatefulWidget {
@override
MyHomePageState createState() {
return new MyHomePageState();
}
}
class MyHomePageState extends State<MyHomePage> {
final _text = TextEditingController();
bool _validate = false;
@override
void dispose() {
_text.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('TextField Demo'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('Error Showed if Field is Empty on Submit button Pressed'),
TextField(
controller: _text,
decoration: InputDecoration(
labelText: 'Enter the Value',
errorText: _validate ? 'Value Can\'t Be Empty' : null,
),
),
RaisedButton(
onPressed: () {
setState(() {
_text.text.isEmpty ? _validate = true : _validate = false;
});
},
child: Text('Submit'),
textColor: Colors.white,
color: Colors.blueAccent,
)
],
),
),
);
}
}
当用户未在 TextField 中输入任何内容时,此代码会显示错误文本
推荐阅读
- sql - UNPIVOT 没有得到 NULL 值
- sql-server - SQL Server 中的结果集数量是否受到限制?
- specflow - 尽管有 catch 块,Specflow 3.1 仍会抛出测试失败消息
- java - Java REST 客户端 - 错误请求 (400) - 由于语法错误,服务器无法理解请求
- python-3.x - 计数来自另一列的 Id 的总行数
- asp.net - ASP.Net Core 3.1 - IIS 10.0 - Windows 身份验证
- angular - 如何以角度 4 读取/保存 HTTP Post 响应(HTML 格式)
- sql - 我想在我的 SQL 表中连接多个 ID
- java - Spring Boot 安全 - 基本身份验证
- javascript - 来自 localhost 的 GET 返回代码 404(未找到)