为什么未验证表格?验证器的颤动形式验证

发布于 2025-01-21 14:11:27 字数 3890 浏览 4 评论 0原文

import 'package:flutter/material.dart';
import 'package:sumanthk07/utilities/routes.dart';

class LoginPage extends StatefulWidget {
const LoginPage({Key? key}) : super(key: key);

@override
State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
final _formkey = GlobalKey<FormState>();

// ignore: avoid_types_as_parameter_names, non_constant_identifier_names
moveToHome(BuildContext) async{
Navigator.pushNamed(context, MyRoutes.homeRoute);
}

 @override
Widget build(BuildContext context) {
  return Material(
    color: Colors.white,
    child: SingleChildScrollView(
    child: Form(
       key: _formkey,
      child: Column(
        children: [
          Image.asset("assets/images/login.png", fit: BoxFit.cover),
          const SizedBox(
            height: 20.0,
          ),
          const Text(
            'Welcome',
            style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
          ),
          const SizedBox(
            height: 20.0,
          ),
          Padding(
            padding: const EdgeInsets.symmetric(
                vertical: 16.0, horizontal: 32.0),
            child: Column(
              children: [
                TextFormField(
                  decoration: const InputDecoration(
                      hintText: "Enter User name", labelText: "Username "),
                      initialValue: "",
                  validator: (String? value) {
                    if (value !=null && value.isEmpty ) {
                      return "User name cannot be empty";
                    }
                    return null;
                  },
                  onChanged: (value) {
                    setState(() {});
                  },
                ),
                TextFormField(
                  obscureText: true,
                  decoration: const InputDecoration(
                      hintText: "Enter password", labelText: "Password "),
                      initialValue: "",
                  validator: (String? value) {
                    if (value !=null && value.isEmpty ) {
                      return "Password name cannot be empty";
                    }
                    return null;
                  },
                ),
                const SizedBox(
                  height: 20.0,
                ),

                InkWell(
                  onTap: () => moveToHome(context),
                  child: AnimatedContainer(
                    duration: const Duration(seconds: 1),
                    height: 40,
                    width: 80,
                    alignment: Alignment.center,
                    child: const Text("Login",
                        style: TextStyle(
                          color: Colors.white,
                          fontWeight: FontWeight.bold,
                          fontSize: 18,
                        )),
                    decoration: BoxDecoration(
                        color: Colors.red,
                        // ignore: unnecessary_const
                        borderRadius: BorderRadius.circular(20)),
                  ),
                )

                // ElevatedButton(
                //   child: const Text("Login"),
                //   style: TextButton.styleFrom(),
                //   onPressed: () {
                //     // ignore: unused_local_variable
                //     var myRoutes = MyRoutes;
                //     Navigator.pushNamed(context, MyRoutes.homeRoute);
                //   },
                // )
              ],
            ),
          )
        ],
      ),
    ),
  ),
 );
}

 BorderRadius newMethod() => BorderRadius.circular(20);
 }

大家好,我是一个初学者,我正在尝试将验证器添加到窗口小部件中,但是在运行应用程序时,我没有得到验证。

我搜索并尝试了做到这一点的方法,但没有得到预期的结果。

你们能查看我的代码并以正确的方式提出建议。

没有发现错误,但是验证不起作用。

import 'package:flutter/material.dart';
import 'package:sumanthk07/utilities/routes.dart';

class LoginPage extends StatefulWidget {
const LoginPage({Key? key}) : super(key: key);

@override
State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
final _formkey = GlobalKey<FormState>();

// ignore: avoid_types_as_parameter_names, non_constant_identifier_names
moveToHome(BuildContext) async{
Navigator.pushNamed(context, MyRoutes.homeRoute);
}

 @override
Widget build(BuildContext context) {
  return Material(
    color: Colors.white,
    child: SingleChildScrollView(
    child: Form(
       key: _formkey,
      child: Column(
        children: [
          Image.asset("assets/images/login.png", fit: BoxFit.cover),
          const SizedBox(
            height: 20.0,
          ),
          const Text(
            'Welcome',
            style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
          ),
          const SizedBox(
            height: 20.0,
          ),
          Padding(
            padding: const EdgeInsets.symmetric(
                vertical: 16.0, horizontal: 32.0),
            child: Column(
              children: [
                TextFormField(
                  decoration: const InputDecoration(
                      hintText: "Enter User name", labelText: "Username "),
                      initialValue: "",
                  validator: (String? value) {
                    if (value !=null && value.isEmpty ) {
                      return "User name cannot be empty";
                    }
                    return null;
                  },
                  onChanged: (value) {
                    setState(() {});
                  },
                ),
                TextFormField(
                  obscureText: true,
                  decoration: const InputDecoration(
                      hintText: "Enter password", labelText: "Password "),
                      initialValue: "",
                  validator: (String? value) {
                    if (value !=null && value.isEmpty ) {
                      return "Password name cannot be empty";
                    }
                    return null;
                  },
                ),
                const SizedBox(
                  height: 20.0,
                ),

                InkWell(
                  onTap: () => moveToHome(context),
                  child: AnimatedContainer(
                    duration: const Duration(seconds: 1),
                    height: 40,
                    width: 80,
                    alignment: Alignment.center,
                    child: const Text("Login",
                        style: TextStyle(
                          color: Colors.white,
                          fontWeight: FontWeight.bold,
                          fontSize: 18,
                        )),
                    decoration: BoxDecoration(
                        color: Colors.red,
                        // ignore: unnecessary_const
                        borderRadius: BorderRadius.circular(20)),
                  ),
                )

                // ElevatedButton(
                //   child: const Text("Login"),
                //   style: TextButton.styleFrom(),
                //   onPressed: () {
                //     // ignore: unused_local_variable
                //     var myRoutes = MyRoutes;
                //     Navigator.pushNamed(context, MyRoutes.homeRoute);
                //   },
                // )
              ],
            ),
          )
        ],
      ),
    ),
  ),
 );
}

 BorderRadius newMethod() => BorderRadius.circular(20);
 }

Hi All, I'm a beginner to flutter and I'm trying to add validator to widget but I'm not getting the validation when I run the application.

I searched and tried the ways to do it but I didn't get the desired outcome.

Can you guys look into my code and suggest the right way.

no errors found but validation is not working.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

调妓 2025-01-28 14:11:27

首先将TexteditingController分配给您的两个字段。

  final TextEditingController _controllerUserName = TextEditingController();
  final TextEditingController _controllerPassword = TextEditingController();

并且还将AutovalIdateMode分配到您的文本字段,因此您可以在用户输入上验证。它不是可选的,但您可以添加它以在输入字段更改上验证您的字段。尽管您可以在提交时间验证表格。

TextFormField(
              decoration: const InputDecoration(
                  hintText: "Enter User name", labelText: "Username "),
                  initialValue: "",
              validator: (String? value) {
                if (value !=null && value.isEmpty ) {
                  return "User name cannot be empty";
                }
                return null;
              },
              onChanged: (value) {
                setState(() {});
              },
              autovalidate : AutovalidateMode.onUserInteraction,
              controller:_controllerUserName
            ),

而且,您尚未在提交时间验证表格。尝试一下

moveToHome(BuildContext) async{
   if (_formkey.currentState.validate()) {
       Navigator.pushNamed(context, MyRoutes.homeRoute);
   }
 }

First assign TextEditingController to your both fields.

  final TextEditingController _controllerUserName = TextEditingController();
  final TextEditingController _controllerPassword = TextEditingController();

And also assign autovalidateMode to your text field so you can validate at user input like this. It's not necessary it's optional but you can add it to validate your field on input field changes. Although you can validate your form at submission time.

TextFormField(
              decoration: const InputDecoration(
                  hintText: "Enter User name", labelText: "Username "),
                  initialValue: "",
              validator: (String? value) {
                if (value !=null && value.isEmpty ) {
                  return "User name cannot be empty";
                }
                return null;
              },
              onChanged: (value) {
                setState(() {});
              },
              autovalidate : AutovalidateMode.onUserInteraction,
              controller:_controllerUserName
            ),

And also you have not validate your form at submission time. try this

moveToHome(BuildContext) async{
   if (_formkey.currentState.validate()) {
       Navigator.pushNamed(context, MyRoutes.homeRoute);
   }
 }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文