简体   繁体   English

如何在 Flutter 中的 TextFormField 中显示错误文本,而不是在其中

[英]How to show error text in TextFormField in Flutter below it and not in it

I have sign up page where user has to enter info in text form field.我有注册页面,用户必须在文本表单字段中输入信息。 I have added validator that field can't be empty or min of 5 or xyz characters should be entered to pass through.我添加了验证器,该字段不能为空或最少 5 个或 xyz 字符应输入以通过。 My question is how can I make the error message display below the form field rather than in the field.我的问题是如何使错误消息显示在表单字段下方而不是字段中。 this is the code :这是代码:

child: TextFormField(
                                          obscureText: isHidden,
                                          controller: _nameController,
                                          validator: (value) {
                                            RegExp regex = RegExp(r'^.{5,}$');
                                            if (value!.isEmpty) {
                                              return ("Password can't be empty");
                                            }
                                            if (!regex.hasMatch(value)) {
                                              return ("Minimum of 5 characters Required");
                                            }
                                            return null;
                                          },
                                          onSaved: (value) {
                                            shopName.text = value!;
                                          },
                                          
                                          decoration: InputDecoration(
                                            border: InputBorder.none,
                                            errorStyle: TextStyle(
                                                color: Colors.red[400],
                                                fontWeight: FontWeight.bold,
                                                fontSize: 13,
                                                height: 0),
                                            contentPadding:
                                                EdgeInsets.only(left: 15),
                                            // fillColor: Colors.blueAccent,
                                            suffix: Padding(
                                              padding: const EdgeInsets.only(
                                                  right: 8.0),
                                              child: InkWell(
                                                  onTap: _passwdview,
                                                  child: isHidden
                                                      ? const Icon(
                                                          Icons.visibility,
                                                          color: Colors.blue,
                                                          size: 20,
                                                        )
                                                      : const Icon(
                                                          Icons.visibility_off,
                                                          color: Colors.blue,
                                                          size: 20,
                                                        )),
                                            ),
                                            hintText: 'Enter Password',
                                          ),
                                        ),

在此处输入图像描述

I want something like this :我想要这样的东西: 在此处输入图像描述

Use autovalidateMode property.使用autovalidateMode属性。

If AutovalidateMode.onUserInteraction, this FormField will only auto-validate after its content changes.如果是 AutovalidateMode.onUserInteraction,这个 FormField 只会在其内容改变后自动验证。 If AutovalidateMode.always, it will auto-validate even without user interaction.如果 AutovalidateMode.always,即使没有用户交互,它也会自动验证。 If AutovalidateMode.disabled, auto-validation will be disabled.如果 AutovalidateMode.disabled,自动验证将被禁用。

You can checkout the following textfield:您可以签出以下文本字段:

TextFormField(
              onChanged: (value) {},
              onSaved: (value) {},
              focusNode: FocusNode(),
              autofocus: false,
              style: const TextStyle(color: Colors.black, fontSize: 14, fontWeight: FontWeight.w500),
              decoration: InputDecoration(
                fillColor: Colors.grey[300],
                filled: true,
                isDense: true,
                contentPadding: const EdgeInsets.symmetric(vertical: 12.0, horizontal: 16.0),
                // counter: Container(),
                counterText: '',
                hintStyle: const TextStyle(color: Colors.white, fontSize: 14),
                hintText: 'Give me Blood',
                errorBorder: OutlineInputBorder(
                  borderSide: const BorderSide(color: Colors.red),
                  borderRadius: BorderRadius.circular(25.0),
                ),
                focusedErrorBorder: OutlineInputBorder(
                  borderSide: const BorderSide(color: Colors.red),
                  borderRadius: BorderRadius.circular(25.0),
                ),
                focusedBorder: OutlineInputBorder(
                  borderSide: const BorderSide(color: Colors.black),
                  borderRadius: BorderRadius.circular(25.0),
                ),
                enabledBorder: OutlineInputBorder(
                  borderSide: const BorderSide(color: Colors.green),
                  borderRadius: BorderRadius.circular(25.0),
                ),
              ),
              validator: (value) {
                RegExp regex = RegExp(r'^.{5,}$');
                if (value!.isEmpty) {
                  return ("Password can't be empty");
                }
                if (!regex.hasMatch(value)) {
                  return ("Minimum of 5 characters Required");
                }
                return null;
              }),

main.dart file: main.dart文件:

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Padding(
          padding: EdgeInsets.all(30),
          child: MyWidget(),
        ),
      ),
    );
  }
}

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return TextFormField(
      validator: (value) {
        RegExp regex = RegExp(r'^.{5,}$');
        if (value!.isEmpty) {
          return ("Password can't be empty");
        }
        if (!regex.hasMatch(value)) {
          return ("Minimum of 5 characters Required");
        }
        return null;
      },
      autovalidateMode: AutovalidateMode.onUserInteraction,,
      decoration: InputDecoration(
        errorStyle: TextStyle(
            color: Colors.red[400],
            fontWeight: FontWeight.bold,
            fontSize: 13,
            height: 0),
        contentPadding: EdgeInsets.only(left: 15),
        enabledBorder: InputBorders.enabled,
        errorBorder: InputBorders.error,
        focusedErrorBorder: InputBorders.error,
        border: InputBorders.border,
        focusedBorder: InputBorders.focused,
        hintText: 'Enter Password',
      ),
    );
  }
}

constants.dart file constants.dart文件

class InputBorders {
  InputBorders._();

  static const border = OutlineInputBorder(
    borderRadius: Radiuses.r8,
    borderSide: BorderSide(
      color: ColorPalette.strokeGrey,
      width: 0.8,
    ),
  );

  static const enabled = OutlineInputBorder(
    borderRadius: Radiuses.r8,
    borderSide: BorderSide(
      color: ColorPalette.strokeGrey,
      width: 0.8,
    ),
  );

  static const error = OutlineInputBorder(
    borderRadius: Radiuses.r8,
    borderSide: BorderSide(
      color: ColorPalette.red,
      width: 0.8,
    ),
  );

  static const success = OutlineInputBorder(
    borderRadius: Radiuses.r8,
    borderSide: BorderSide(
      color: ColorPalette.greenDark,
      width: 0.8,
    ),
  );

  static const focused = OutlineInputBorder(
    borderRadius: Radiuses.r8,
    borderSide: BorderSide(
      color: ColorPalette.blueLight,
      width: 0.8,
    ),
  );
}

class ColorPalette {
  ColorPalette._();

  static const blueLight = Color(0xFF5599FB);
  static const greenDark = Color(0xFF219653);
  static const red = Color(0xFFFF0033);
  static const strokeGrey = Color(0xFFB4B4B4);
}

class Radiuses {
  Radiuses._();

  static const r8 = BorderRadius.all(Radius.circular(8));
}

Empty State:空状态:

1

Focused State:专注状态:

2

Error State:错误状态:

3

The simplest of all is to use TextFormField with validator最简单的是将TextFormFieldvalidator一起使用

TextFormField(
  // The validator receives the text that the user has entered.
  validator: (value) {
    if (value == null || value.isEmpty) {
      return 'Please enter some text';
    }
    return null;
  },
),

For alternatives,follow the official documentation examples: https://docs.flutter.dev/cookbook/forms/validation对于替代方案,请遵循官方文档示例: https ://docs.flutter.dev/cookbook/forms/validation

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Flutter TextFormField Validator 在文本为空或 null 时显示错误后缀图标 - Flutter TextFormField Validator show error suffixIcon on text empty or null Flutter Textformfield 如何在 Textformfield 中居中文本 - Flutter Textformfield How to center text in a Textformfield 如何使用下拉按钮创建 TextformField 以在 flutter 中显示图标和文本列表 - How to create TextformField with Dropdown button to show list of icons and text in flutter 如何在flutter中的textformfield边界内显示标签和错误消息? - How to show label and error message inside the boundry of textformfield in flutter? 如何使TextFormField文本在validate上显示在TextFormField行下方 - How to make TextFormField text on validate appear below the TextFormField line 如何在 Flutter 中将 TextFormField 的错误文本居中? - How can I center the error text of a TextFormField in Flutter? 在 Flutter 中,如何在表单外(即提交按钮下方)输出 TextFormField 验证器文本? - In Flutter, how do you output TextFormField validator text outside the form (i.e. below submit button)? Flutter TextFormField验证错误文本填充 - Flutter TextFormField Validation Error Text Padding Flutter TextFormField 为错误文本添加填充 - Flutter TextFormField add padding to error text TextFormField 颤动中提示和错误文本的单独 contentPadding - Separate contentPadding for Hint and Error text in TextFormField flutter
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM