简体   繁体   English

Flutter Textfield Validation 消息索引

[英]Flutter Textfield Validation message indexing

I have one form in Flutter, with simple textfield and validation messages.我在 Flutter 中有一个表单,带有简单的文本字段和验证消息。

In textfield there are placeholders which slide up when user focus in particular textfield.在文本字段中有一些占位符,当用户聚焦在特定文本字段时会向上滑动。 at that time if there is a validation message from above field, then placeholder is showing above the validation message.届时,如果有来自上述字段的验证消息,则占位符将显示在验证消息上方。

Here is the Screenshot这是截图

在此处输入图片说明

Here is my Code这是我的代码

 import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, home: Scaffold( backgroundColor: Colors.grey, appBar: AppBar( title: Text("This is App Bar"), ), body: Padding( padding: EdgeInsets.all(10.00), child: Container( padding: EdgeInsets.all(10.00), decoration: BoxDecoration( color: Colors.white, ), child: Column( children: <Widget>[ Container( child: Stack( overflow: Overflow.visible, children: <Widget>[ TextField(), Positioned( left: 0.0, top: 45.0, child: Container( padding: EdgeInsets.only( left: 5, right: 5, top: 1, bottom: 3), decoration: BoxDecoration( color: Colors.red, borderRadius: BorderRadius.only( bottomLeft: const Radius.circular(5.0), bottomRight: const Radius.circular(5.0)), boxShadow: [ new BoxShadow( color: Colors.grey[300], blurRadius: 5.0, ), ]), child: Text("Validation Message"), ), ) ], )), Container( child: Stack( overflow: Overflow.visible, children: <Widget>[ TextField(), Positioned( left: 0.0, top: 45.0, child: Container( padding: EdgeInsets.only( left: 5, right: 5, top: 1, bottom: 3), decoration: BoxDecoration( color: Colors.red, borderRadius: BorderRadius.only( bottomLeft: const Radius.circular(5.0), bottomRight: const Radius.circular(5.0)), boxShadow: [ new BoxShadow( color: Colors.grey[300], blurRadius: 5.0, ), ]), child: Text("Validation Message"), ), ) ], )), ], ), ), )), ); } }

You can utilize TextFormField's validator to check the String inputted on the field.您可以利用 TextFormField 的验证器来检查在字段上输入的字符串。

/// Initialize TextField validator message status
List<bool> _textFieldError = [false, false];

...

TextFormField(
  validator: (text) {
    if (text == null || text.isEmpty) {
      setState(() {
        /// Update boolean to determine if the validator message should be displayed
        _textFieldError[0] = true;
      });
      /// Returning a String on validator displays it as a message on the top of the TextFormField
      return '';
    }
    setState(() {
      _textFieldError[0] = false;
    });
    return null;
    },
    onFieldSubmitted: (value) {
      /// Calling Form.validate() will run all validator on the Form's TextFormField children
      _formKey.currentState!.validate();
    },
  ),
  ...
)

Add a bool check to identify if the validator message should be displayed.添加 bool 检查以确定是否应显示验证器消息。

_textFieldError[0]
  ? ValidatorMessage // Display validator message
  : const SizedBox(), // Display none

Here's the complete code based from the repro provided.这是基于提供的 repro 的完整代码。

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final _formKey = GlobalKey<FormState>();
  List<bool> _textFieldError = [false, false];

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
          backgroundColor: Colors.grey,
          appBar: AppBar(
            title: const Text("This is App Bar"),
          ),
          body: Padding(
            padding: const EdgeInsets.all(10.00),
            child: Container(
              padding: const EdgeInsets.all(10.00),
              decoration: const BoxDecoration(
                color: Colors.white,
              ),
              child: Form(
                key: _formKey,
                child: Column(
                  children: <Widget>[
                    Container(
                      child: Stack(
                        overflow: Overflow.visible,
                        children: <Widget>[
                          TextFormField(
                            validator: (text) {
                              if (text == null || text.isEmpty) {
                                setState(() {
                                  _textFieldError[0] = true;
                                });
                                return '';
                              }
                              setState(() {
                                _textFieldError[0] = false;
                              });

                              return null;
                            },
                            onFieldSubmitted: (value) {
                              _formKey.currentState!.validate();
                            },
                          ),
                          _textFieldError[0]
                              ? Positioned(
                                  left: 0.0,
                                  top: 45.0,
                                  child: Container(
                                    padding: const EdgeInsets.only(
                                        left: 5, right: 5, top: 1, bottom: 3),
                                    decoration: BoxDecoration(
                                        color: Colors.red,
                                        borderRadius: const BorderRadius.only(
                                            bottomLeft: Radius.circular(5.0),
                                            bottomRight: Radius.circular(5.0)),
                                        boxShadow: [
                                          BoxShadow(
                                            color: Colors.grey.shade300,
                                            blurRadius: 5.0,
                                          ),
                                        ]),
                                    child: const Text("Validation Message"),
                                  ),
                                )
                              : const SizedBox(),
                        ],
                      ),
                    ),
                    Container(
                        child: Stack(
                      clipBehavior: Clip.none,
                      // overflow: Overflow.visible,
                      children: <Widget>[
                        TextFormField(
                          validator: (text) {
                            if (text == null || text.isEmpty) {
                              setState(() {
                                _textFieldError[1] = true;
                              });
                              return '';
                            }
                            setState(() {
                              _textFieldError[1] = false;
                            });
                            return null;
                          },
                          onFieldSubmitted: (value) {
                            _formKey.currentState!.validate();
                          },
                        ),
                        Positioned(
                          left: 0.0,
                          top: 45.0,
                          child: _textFieldError[1]
                              ? Container(
                                  padding: const EdgeInsets.only(
                                      left: 5, right: 5, top: 1, bottom: 3),
                                  decoration: BoxDecoration(
                                      color: Colors.red,
                                      borderRadius: const BorderRadius.only(
                                          bottomLeft: Radius.circular(5.0),
                                          bottomRight: Radius.circular(5.0)),
                                      boxShadow: [
                                        BoxShadow(
                                          color: Colors.grey.shade300,
                                          blurRadius: 5.0,
                                        ),
                                      ]),
                                  child: const Text("Validation Message"),
                                )
                              : const SizedBox(),
                        )
                      ],
                    )),
                  ],
                ),
              ),
            ),
          )),
    );
  }
}

演示

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM