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用于指定如何构建错误文本小部件。
  • errorTextAnchortextFieldAnchor以及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 回复

更多关于Flutter自定义错误文本表单字段插件custom_error_text_form_field的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


在 Flutter 中,你可以通过自定义 TextFormField 来创建一个带有自定义错误文本的表单字段插件。以下是一个简单的示例,展示了如何创建一个 CustomErrorTextFormField 插件,并演示如何使用它。

1. 创建 CustomErrorTextFormField 插件

首先,创建一个新的 Dart 文件,例如 custom_error_text_form_field.dart,并定义一个 CustomErrorTextFormField 类:

import 'package:flutter/material.dart';

class CustomErrorTextFormField extends StatelessWidget {
  final TextEditingController controller;
  final String? labelText;
  final String? hintText;
  final String? errorText;
  final FormFieldValidator<String>? validator;
  final ValueChanged<String>? onChanged;

  const CustomErrorTextFormField({
    Key? key,
    required this.controller,
    this.labelText,
    this.hintText,
    this.errorText,
    this.validator,
    this.onChanged,
  }) : super(key: key);

  [@override](/user/override)
  Widget build(BuildContext context) {
    return TextFormField(
      controller: controller,
      decoration: InputDecoration(
        labelText: labelText,
        hintText: hintText,
        errorText: errorText,
      ),
      validator: validator,
      onChanged: onChanged,
    );
  }
}

2. 使用 CustomErrorTextFormField 插件

接下来,你可以在你的 Form 中使用这个自定义的 CustomErrorTextFormField。以下是一个简单的示例:

import 'package:flutter/material.dart';
import 'custom_error_text_form_field.dart';

class MyForm extends StatefulWidget {
  [@override](/user/override)
  _MyFormState createState() => _MyFormState();
}

class _MyFormState extends State<MyForm> {
  final _formKey = GlobalKey<FormState>();
  final _controller = TextEditingController();
  String? _errorText;

  void _validateForm() {
    if (_formKey.currentState!.validate()) {
      // Form is valid, proceed with further actions
      print('Form is valid');
    }
  }

  String? _validateField(String? value) {
    if (value == null || value.isEmpty) {
      setState(() {
        _errorText = 'This field is required';
      });
      return 'This field is required';
    }
    setState(() {
      _errorText = null;
    });
    return null;
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Custom Error TextFormField Example'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Form(
          key: _formKey,
          child: Column(
            children: [
              CustomErrorTextFormField(
                controller: _controller,
                labelText: 'Enter your name',
                hintText: 'John Doe',
                errorText: _errorText,
                validator: _validateField,
                onChanged: (value) {
                  _validateField(value);
                },
              ),
              SizedBox(height: 20),
              ElevatedButton(
                onPressed: _validateForm,
                child: Text('Submit'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

void main() {
  runApp(MaterialApp(
    home: MyForm(),
  ));
}
回到顶部