flutter - 文本表单字段验证器错误消息未显示

标签 flutter dart

我期望如果更多验证器之一返回字符串,则TextFormField的验证器将显示错误消息。但是,尽管已实现它们,但即使在满足条件之后,它们仍会以某种方式无法显示错误消息(例如value.length> = 3)。

                      Form(
                        key: formKey,
                        child: Column(
                          children: <Widget>[
                            TextFormField(
                              // validator fails to display its error message
                              validator: (value) => value.length >= 3 ? null : "Username must consist of at least 3 characters.",
                              decoration: InputDecoration(
                                filled: true,
                                fillColor: Colors.black12,
                                hintText: "Username *",
                                hintStyle: hintTextStyle,
                                border: OutlineInputBorder(
                                  borderRadius: BorderRadius.circular(15.0),
                                )
                              ),
                              maxLines: 1,
                              controller: usernameController
                            ),
                            SizedBox(height: 20.0),
                            TextFormField(
                              // validator fails to display its error message
                              validator: (value) {
                                return RegExp(
                                    r"^[a-zA-Z0-9.a-zA-Z0-9.!#$%&'*+-/=?^_`{|}~]+@[a-zA-Z0-9]+\.[a-zA-Z]+"
                                ).hasMatch(value) ? null : "Please enter a valid email address.";
                              },
                              decoration: InputDecoration(
                                  filled: true,
                                  fillColor: Colors.black12,
                                  hintText: "Email *",
                                  hintStyle: hintTextStyle,
                                  border: OutlineInputBorder(
                                      borderRadius: BorderRadius.circular(15.0),
                                  )
                              ),
                              maxLines: 1,
                              controller: emailController
                            ),
                            SizedBox(height: 20.0),
                            TextFormField(
                              // validator fails to display its error message
                              validator: (value) => value.length >= 6 ? null : "Password must be at least 6 characters and contains both letter and number.",
                              decoration: InputDecoration(
                                  filled: true,
                                  fillColor: Colors.black12,
                                  hintText: "Password *",
                                  hintStyle: hintTextStyle,
                                  border: OutlineInputBorder(
                                      borderRadius: BorderRadius.circular(15.0),
                                  )
                              ),
                              maxLines: 1,
                              obscureText: true,
                              controller: passwordController
                            ),
                            SizedBox(height: 20.0),
                            TextFormField(
                              // validator fails to display its error message
                              validator: (value) => value == passwordController.text ? null : "Password does not match.",
                              decoration: InputDecoration(
                                filled: true,
                                fillColor: Colors.black12,
                                hintText: "Repeat password *",
                                hintStyle: hintTextStyle,
                                border: OutlineInputBorder(
                                  borderRadius: BorderRadius.circular(15.0),
                                )
                              ),
                              maxLines: 1,
                              obscureText: true,
                              controller: repeatPasswordController
                            ),
                            Container(
                                margin: EdgeInsets.symmetric(vertical: 20.0),
                                width: double.infinity,
                                child: RaisedButton(
                                  padding: EdgeInsets.symmetric(vertical: 20.0),
                                  shape: RoundedRectangleBorder(
                                    borderRadius: BorderRadius.circular(15.0),
                                  ),
                                  color: Colors.blueAccent,
                                  child: Text("Sign Up", style: Theme.of(context).textTheme.bodyText1),
                                  onPressed: () => signUpCurrentUser(emailController.text, passwordController.text),
                                )
                            )
                            // irrelevant widgets goes below..
这是注册功能
signUpCurrentUser(String email, String password) {
    authentication.signUp(email, password).then((val) {
      if(formKey.currentState.validate()) {
        setState(() => isLoading = true);

        if(val != null)
          Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) => HomeScreen()));
        else
          setState(() => isLoading = false);
      }
    });
  }
以下是如果我在TextFormField保留为空的情况下单击“注册”按钮时在控制台中返回的内容,但是我认为这与错误无关。
Performing hot reload...
Syncing files to device iPhone 11 Pro Max...
Reloaded 4 of 513 libraries in 355ms.
[VERBOSE-2:ui_dart_state.cc(157)] Unhandled Exception: PlatformException(ERROR_WEAK_PASSWORD, The password must be 6 characters long or more., null)
#0      StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:569:7)
#1      MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:156:18)
<asynchronous suspension>
#2      MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:329:12)
#3      MethodChannel.invokeMapMethod (package:flutter/src/services/platform_channel.dart:356:48)
#4      MethodChannelFirebaseAuth.createUserWithEmailAndPassword (package:firebase_auth_platform_interface/src/method_channel_firebase_auth.dart:64:23)
#5      FirebaseAuth.createUserWithEmailAndPassword (package:firebase_auth/src/firebase_auth.dart:64:10)
#6      AuthMethods.signUp (package:apui/services/authentication.dart:8:39)
#7      _SignupScreenState.signUpCurrentUser (package:apui/screens/signup_screen.dart:27:20)
#8      _SignupScreenStat<…>
Application finished.

最佳答案

需要在注册 按钮 formKey.currentState.validate()函数中调用onPressed
示例代码段如下:

import 'package:flutter/material.dart';

class DummyPage extends StatefulWidget {
  @override
  _DummyPageState createState() => _DummyPageState();
}

class _DummyPageState extends State<DummyPage> {
  TextEditingController usernameController = TextEditingController();
  GlobalKey<FormState> formKey = GlobalKey<FormState>();
  @override
  Widget build(BuildContext context) {
    return Material(
      child: Container(
        child: Form(
          key: formKey,
          child: Column(
            children: <Widget>[
              TextFormField(
                // validator fails to display its error message
                validator: (value) => value.length >= 3
                    ? null
                    : "Username must consist of at least 3 characters.",
                decoration: InputDecoration(
                    filled: true,
                    fillColor: Colors.black12,
                    hintText: "Username *",
                    // hintStyle: hintTextStyle,
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(15.0),
                    )),
                maxLines: 1,
                controller: usernameController,
              ),
              RaisedButton(
                child: Text('Submit'),
                onPressed: () {
                  if (formKey.currentState.validate()) {
                    print(usernameController.text);
                  }
                },
              )
            ],
          ),
        ),
      ),
    );
  }
}

关于flutter - 文本表单字段验证器错误消息未显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62495472/

相关文章:

android - 任务 ':app:transformClassesWithMultidexlistForDebug' 执行失败。在 flutter 中

dart - RxDart 是否支持背压?

ios - 在 Flutter 插件中从 Objective-C 加载原生 C 库

datatable - Flutter DataTable - 点击行

firebase - “task.future.then ”不断在我的Flutter代码中引发错误

dart - 获取Dart中Timer的剩余时间

dart - 如何在 Dart 中生成一个不包含特定编号的随机数?

flutter - 获取屏幕抖动的物理尺寸

flutter - Flutter无法将参数类型 'Listenable'分配给参数类型'Animation <double>

flutter - 如果我在 Flutter 中只使用一些 Statefulwidgets 会怎样?