сообщения об ошибках валидатора поля текстовой формы не отображаются - PullRequest
1 голос
/ 21 июня 2020

Я ожидаю, что валидаторы из TextFormField s будут отображать сообщения об ошибках, если один или несколько валидаторов вернут строку. Но, несмотря на их реализацию, они по-прежнему не могут отображать сообщения об ошибках даже после выполнения условия (например, 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 s остаются пустыми, однако я думаю, что это не имеет отношения к ошибке.

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.

1 Ответ

0 голосов
/ 21 июня 2020

Необходимо позвонить 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);
                  }
                },
              )
            ],
          ),
        ),
      ),
    );
  }
}
...