Flutter自定义错误文本表单字段插件custom_error_text_form_field的使用
Flutter自定义错误文本表单字段插件custom_error_text_form_field的使用
特性
这个包提供了一个CustomErrorTextFormField
小部件,它会在表单字段无效时将错误消息作为覆盖显示,而不是像TextFormField
默认行为那样在表单字段下方显示错误消息并修改布局。
使用方法
CustomErrorTextFormField
具有与TextFormField
相同的参数,但额外提供了四个参数:
final Widget Function(String) errorTextBuilder;
final Alignment errorTextAnchor;
final Alignment textFieldAnchor;
final Offset errorTextOffset;
errorTextBuilder
用于指定如何构建错误文本小部件。errorTextAnchor
和textFieldAnchor
以及errorTextOffset
用于确定错误文本小部件相对于表单字段的位置。
完整示例代码
import 'package:custom_error_text_form_field/custom_error_text_form_field.dart';
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// 这个小部件是你的应用的根节点。
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
[@override](/user/override)
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: Text(widget.title),
),
body: Column(
children: List.generate(
10,
(_) => CustomErrorTextFormField(
validator: (val) {
if (val != null && val.isNotEmpty) {
return 'Text is not empty'; // 如果文本不为空,则返回错误信息。
}
return null; // 否则返回null表示验证通过。
},
autovalidateMode: AutovalidateMode.onUserInteraction, // 用户交互后自动验证。
errorTextBuilder: (text) {
return Container(
decoration: BoxDecoration(
color: Theme.of(context)
.colorScheme
.error
.withOpacity(0.1), // 设置背景颜色和透明度。
borderRadius: BorderRadius.circular(8), // 设置圆角。
border: Border.all(
color: Theme.of(context).colorScheme.error, // 设置边框颜色。
width: 1, // 设置边框宽度。
),
),
padding: const EdgeInsets.symmetric(horizontal: 4), // 设置内边距。
child: Text(
text,
style: Theme.of(context).textTheme.bodyLarge?.copyWith(
color: Theme.of(context).colorScheme.error, // 设置文本颜色。
),
),
);
},
errorTextAnchor: Alignment.centerRight, // 错误文本锚点。
textFieldAnchor: Alignment.centerRight, // 表单字段锚点。
errorTextOffset: const Offset(-8, 0), // 错误文本偏移量。
),
),
),
);
}
}
更多关于Flutter自定义错误文本表单字段插件custom_error_text_form_field的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
1 回复