0

我有一个 textformfield 验证最小长度至少为 3 个字符。稍后,我将使用后端验证用户名是唯一的。

但目前,我无法为 2 个错误显示 2 个错误文本。即,一个用于最小长度(“请为您的用户名输入至少 3 个字符”)和一个用于非唯一用户名(“您的用户名很受欢迎,请尝试另一个。”)

问题:

  • 如何使后缀图标仅在输入至少 1 个字符时出现?而不是默认情况下,我知道它链接到 hasMinLengthUnique = false。

  • 如何为各个错误显示不同的错误文本?

  • 以及稍后,如何根据值 hasMinLengthUnique = true 在导航到另一个页面上放置一个三元运算符。

Bcos 现在,无论 hasMinLengthUnique = true 还是 false,导航都不会发生。

Form(
                  key: _formKey,
                  autovalidateMode: AutovalidateMode.always,
                  child: TextFormField(
                    controller: _controller,
                    validator: (value) {
                      return (0 < value.length && value.length < 3)
                          ? "Please enter at least 3 characters for your username"
                          : null;
                    },
                    onChanged: (value) {
                      setState(() {
                        value.length > 2

                            // && username must be unique

                            ? hasMinLengthUnique = true
                            : hasMinLengthUnique = false;
                      });
                    },
                    style: TextStyle(color: Colors.white),
                    autofocus: true,
                    maxLength: 15,
                    decoration: InputDecoration(
                      suffix: hasMinLengthUnique
                          ? IconButton(
                              icon:
                                  Icon(Icons.check_circle, color: Colors.green))
                          : IconButton(
                              icon: Icon(Icons.cancel, color: Colors.red)),
                      errorBorder: UnderlineInputBorder(
                        borderSide: BorderSide(color: Colors.blue, width: 1.0),
                      ),
                      errorStyle: TextStyle(color: Color(0xff4aa3f8)),
                      focusedErrorBorder: UnderlineInputBorder(
                        borderSide: BorderSide.none,
                      ),
                      border: OutlineInputBorder(),
                      focusedBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.all(Radius.circular(15)),
                        // borderSide: BorderSide(width: 1, color: Colors.white),
                      ),
                    ),
                  ),
                ),
              ),
            ),
            SizedBox(
              height: MediaQuery.of(context).size.height * 0.18,
            ),
            Padding(
                padding: EdgeInsets.only(
                  right: MediaQuery.of(context).size.height * 0.015,
                ),
                child: DelayedDisplay(
                  delay: Duration(seconds: 3),
                  child: Align(
                      alignment: Alignment.centerRight,
                      child: ElevatedButton(
                          style: ElevatedButton.styleFrom(
                              onPrimary: Colors.white,
                              primary: Color(0xff3a327f)),
                          child: Icon(Icons.chevron_right, size: 27),
                          onPressed: () async {
                            // if (formKey.currentState.validate()) {
                            Navigator.push(context, _createRoute());
                            // }
                          })),
                ))
          ]),
        ));

页面截图

4

2 回答 2

1

您是否尝试过 onChanged Value 中的 if else 语句

var isValidate; 
onChanged(){
if(1st condition){
setState(){}
}
else if(2nd condition){
setState(){}
}
}

于 2021-05-21T05:21:59.233 回答
1

这是代码

  1. 它检查用户名是否大于 2
  2. 然后它将检查您的用户名是否受欢迎(尝试输入 admin)
  3. 它会hasMinLengthUnique相应地更新您的用户界面IconButton()
  4. 它也会更新你ElevatedButton()的。如果hasMinLengthUnique为假则变为禁用,如果hasMinLengthUnique为真则变为启用。
import 'package:flutter/material.dart';

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

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

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  bool hasMinLengthUnique = false;
  var _controller = TextEditingController();
  GlobalKey<FormState> _formKey = GlobalKey();
  var defUsername = ["admin"];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Container(
          color: Colors.lightBlue[900],
          child: Column(
            children: [
              Form(
                key: _formKey,
            autovalidateMode: AutovalidateMode.always,
            child: Padding(
              padding: const EdgeInsets.all(8.0),
              child: TextFormField(
                controller: _controller,
                validator: (value) {
                  if (value.length < 3) {
                    return "Please enter at least 3 characters for your username";
                  }
                  if (value.contains(defUsername[0])) {
                    return "Username is too popular";
                  }
                  return null;
                },
                onChanged: (value) {
                  setState(() {
                    if (value.contains(defUsername[0]) ||
                        value.length <= 2) {
                      hasMinLengthUnique = false;
                    } else {
                      hasMinLengthUnique = true;
                    }
                  });
                },
                style: TextStyle(color: Colors.white),
                autofocus: true,
                maxLength: 15,
                decoration: InputDecoration(
                  contentPadding:
                      EdgeInsets.symmetric(vertical: 0, horizontal: 10),
                  labelText: "Username",
                  suffix: hasMinLengthUnique
                      ? Icon(Icons.check_circle, color: Colors.green)
                      : _controller.text.isEmpty
                          ? Icon(null, color: Colors.red)
                          : Icon(Icons.cancel, color: Colors.red),
                  border: OutlineInputBorder(),
                ),
              ),
            ),
              ),
              SizedBox(
                height: MediaQuery.of(context).size.height * 0.18,
              ),
              Padding(
                padding: EdgeInsets.only(
                  right: MediaQuery.of(context).size.height * 0.015,
                ),
                child: Container(
                  child: Align(
                    alignment: Alignment.centerRight,
                    child: ElevatedButton(
                      style: ElevatedButton.styleFrom(
                          onPrimary: Colors.white, primary: Color(0xff3a327f)),
                      child: Icon(Icons.chevron_right, size: 27),
                      onPressed: hasMinLengthUnique
                          ? () {
                              print("go to next screen");
                            }
                          : null,
                    ),
                  ),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}

谢谢!

于 2021-05-21T06:08:24.420 回答