常用属性
- obscureText,密码类型,隐藏输入内容。
- autofocus,自动弹出键盘。
- inputFormatters,允许输入的类型。
- FilteringTextInputFormatter.digitsOnly,只允许输入数字。
FilteringTextInputFormatter.allow(RegExp(r'([1-9]\d*\.?\d*)|(0\.\d*[1-9])'))
,匹配最多 1 个小数点的数字。
- keyboardType: TextInputType.number,键盘类型(数字类型)。
textInputAction: TextInputAction.next
,enter 键改成 next,点击后自动到下一个 TextField。- border,当为
InputBorder.none
的时候,不会显示底部横线。 - InputDecoration
- fillColor,背景色。
- prefixIconConstraints,prefixIcon 的尺寸。
细节
- 包裹 SizedBox() 改变尺寸。
默认值
TextEditingController _textFieldController = TextEditingController();
content: TextField(
controller: _textFieldController,
decoration: InputDecoration(hintText: "请输入 Todoist API Token"),
),
],
_textFieldController.text = todoistAPIToken;
点 Enter 的时候关闭 Dialog
onSubmitted: (value) async {
await onSaveToken(context);
},
Future onSaveToken(BuildContext context) async {
final token = _todoistTokenTextFieldController.text;
setState(() {
todoistAPIToken = token;
});
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString(
SharedPreferencesConstants.TodoistAPIToken, token);
Navigator.pop(context);
}
添加清空按钮
decoration: InputDecoration(
suffixIcon: IconButton(
onPressed: _todoistTokenTextFieldController.clear,
icon: Icon(Icons.clear),
),
)
宽度适配输入的文本宽度并强制最小宽度
ConstrainedBox(
constraints: BoxConstraints(minWidth: 48),
child: IntrinsicWidth(
child: TextField(),
),
)
换行
_buildTextField() {
return TextField(
keyboardType: TextInputType.multiline,
maxLines: null,
decoration: InputDecoration(
contentPadding: EdgeInsets.all(15),
hintText: '本店营业时间:8:00-18:00',
hintStyle: TextStyle(color: HexColor('#999999'), fontSize: 14),
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide.none,
),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide.none,
),
),
);
}
使用 GetX 监听内容变化
class FeedbackController extends GetxController {
TextEditingController feedbackTextController = TextEditingController();
final feedback = ''.obs;
@override
void onInit() {
feedbackTextController.addListener(() {
feedback.value = feedbackTextController.text;
});
super.onInit();
}
@override
void onClose() {
feedbackTextController.dispose();
super.onClose();
}
}
prefix 一直显示
用 prefixIcon 替代 prefix。
解决输入的内容没有居中
decoration: InputDecoration(
contentPadding: EdgeInsets.all(10.r),
)