Flutter 中的 TextFormField 小部件:全面指南
warning:
这篇文章距离上次修改已过203天,其中的内容可能已经有所变动。
在Flutter中,TextFormField
是一个非常常用的小部件,它是FormField
的一个特殊版本,用于创建文本输入表单字段。以下是一个简单的TextFormField
使用指南和示例代码:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('TextFormField Example'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Form(
key: _formKey,
child: TextFormField(
decoration: InputDecoration(
labelText: 'Enter your username',
helperText: 'Please enter your username',
),
validator: (String value) {
if (value.isEmpty) {
return 'Username is required';
}
return null;
},
),
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
if (_formKey.currentState.validate()) {
// Process data.
print(_formKey.currentState.value);
}
},
child: Icon(Icons.send),
),
),
);
}
}
这段代码创建了一个带有TextFormField
的简单表单,用户可以在其中输入他们的用户名。validator
属性用于验证输入的数据是否有效,如果输入为空,则返回错误消息。Form
小部件的_formKey
用于管理表单状态,可以通过_formKey.currentState.validate()
来触发验证过程。如果数据有效,可以在onPressed
回调中处理数据。
评论已关闭