具有零安全性的 flutter 表单验证器

标签 flutter dart authentication dart-null-safety

我在尝试在登录屏幕上创建表单验证器时遇到问题,当我录制登录并且文本字段已经为空时,它不起作用。这是我的代码,如果您有任何帮助,我会这样做: TextFormField 验证参数采用一个函数,如果字段内容有效,则返回 null;如果内容无效,则返回字符串。我的 flutter 项目中有 null 安全性,并且无法从验证函数中返回 null。如何编写一个启用 null 安全性的工作验证函数?

登录代码屏幕:

import 'package:flutter/material.dart';
import 'package:flutter_udemy/shared/components/components.dart';

class LoginScreen extends StatefulWidget {
LoginScreen({Key? key}) : super(key: key);
@override
_LoginScreenState createState() => _LoginScreenState();
}

class _LoginScreenState extends State<LoginScreen> {
var emailController = TextEditingController();
var passwordController = TextEditingController();
var formKey = GlobalKey<FormState>();
bool isPassword = true;

@override
Widget build(BuildContext context) {
return Scaffold(
  appBar: AppBar(),
  body: Padding(
    padding: const EdgeInsets.all(20.0),
    child: Center(
      child: SingleChildScrollView(
        child: Form(
          key: formKey,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                'Login',
                style: TextStyle(
                  fontSize: 40.0,
                  fontWeight: FontWeight.bold,
                ),
              ),
              SizedBox(
                height: 40.0,
              ),
              defaultFormField(
                controller: emailController,
                label: 'Email',
                prefix: Icons.email,
                type: TextInputType.emailAddress,
                validate: (String value) {
                  if (value.isEmpty) {
                    return 'email must not be empty';
                  }

                  return null;
                },
              ),
              SizedBox(
                height: 15.0,
              ),
              defaultFormField(
                controller: passwordController,
                label: 'Password',
                prefix: Icons.lock,
                suffix:
                    isPassword ? Icons.visibility : Icons.visibility_off,
                isPassword: isPassword,
                suffixPressed: () {
                  setState(() {
                    isPassword = !isPassword;
                  });
                },
                type: TextInputType.visiblePassword,
                validate: (String value) {
                  if (value.isEmpty) {
                    return 'password is too short';
                  }
                  return null;
                },
              ),
              SizedBox(
                height: 20.0,
              ),
              defaultButton(
                text: 'login',
                function: () {
                  if (formKey.currentState!.validate()) {
                    print(emailController.text);
                    print(passwordController.text);
                  }
                },
              ),
              SizedBox(
                height: 20.0,
              ),
              defaultButton(
                text: 'ReGIster',
                function: () {
                  print(emailController.text);
                  print(passwordController.text);
                },
              ),
              SizedBox(
                height: 10.0,
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    'Don\'t have an account?',
                  ),
                  TextButton(
                    onPressed: () {},
                    child: Text(
                      'Register Now',
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
     ),
    ),
   );
   }
  }

组件代码屏幕,我在其中获得了按钮小部件和文本字段小部件:

 import 'package:flutter/material.dart';

   Widget defaultButton({
  double width = double.infinity,
  Color background = Colors.blue,
  bool isUpperCase = true,
  double radius = 10.0,
   required Function function,
    required String text,
   }) =>
       Container(
       width: width,
       height: 50.0,
        child: MaterialButton(
        onPressed: () {
       function();
     },
     child: Text(
      isUpperCase ? text.toUpperCase() : text,
      style: TextStyle(
        color: Colors.white,
      ),
    ),
  ),
  decoration: BoxDecoration(
    borderRadius: BorderRadius.circular(
      radius,
    ),
    color: background,
  ),
);

   Widget defaultFormField({
  required TextEditingController controller,
  required TextInputType type,
  Function? onSubmit,
   Function? onChange,
     bool isPassword = false,
   required Function validate,
   required String label,
   required IconData prefix,
   IconData? suffix,
   Function? suffixPressed,
     }) =>
    TextFormField(
     controller: controller,
    keyboardType: type,
    obscureText: isPassword,
    onFieldSubmitted: (s) {
      onSubmit!(s);
    },
  onChanged: (s) {
    onChange!(s);
  },
  validator: (s) {
    validate(s);
  },
  decoration: InputDecoration(
    labelText: label,
    prefixIcon: Icon(
      prefix,
    ),
    suffixIcon: suffix != null
        ? IconButton(
            onPressed: () {
              suffixPressed!();
            },
            icon: Icon(
              suffix,
            ),
          )
        : null,
    border: OutlineInputBorder(),
  ),
);

最佳答案

此代码有效
针对 null 安全性所做的主要更改
必需的字符串?函数(字符串?)?验证

validate: (String? value) {
   if (value!.isEmpty) 
   {
        return 'email must not be empty';
   }
       return null;
   },

完整代码如下

class LoginScreen extends StatefulWidget {
LoginScreen({Key? key}) : super(key: key);
@override
_LoginScreenState createState() => _LoginScreenState();
}

class _LoginScreenState extends State<LoginScreen> {
var emailController = TextEditingController();
var passwordController = TextEditingController();
final formKey = GlobalKey<FormState>();
bool isPassword = true;

@override
Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar(),
    body: Padding(
    padding: const EdgeInsets.all(20.0),
    child: Center(
      child: SingleChildScrollView(
        child: Form(
          key: formKey,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                'Login',
                style: TextStyle(
                  fontSize: 40.0,
                  fontWeight: FontWeight.bold,
                ),
              ),
              SizedBox(
                height: 40.0,
              ),
              defaultFormField(
                controller: emailController,
                label: 'Email',
                prefix: Icons.email,
                type: TextInputType.emailAddress,
                validate: (String? value) {
                  if (value!.isEmpty) {
                    return 'email must not be empty';
                  }

                  return null;
                },
              ),
              SizedBox(
                height: 15.0,
              ),
              defaultFormField(
                controller: passwordController,
                label: 'Password',
                prefix: Icons.lock,
                suffix:
                    isPassword ? Icons.visibility : Icons.visibility_off,
                isPassword: isPassword,
                suffixPressed: () {
                  setState(() {
                    isPassword = !isPassword;
                  });
                },
                type: TextInputType.visiblePassword,
                validate: (String? value) {
                  if (value!.isEmpty) {
                    return 'password is too short';
                  }
                  return null;
                },
              ),
              SizedBox(
                height: 20.0,
              ),
              defaultButton(
                text: 'login',
                function: () {
                  if (formKey.currentState!.validate()) {
                    print(emailController.text);
                    print(passwordController.text);
                  }
                },
              ),
              SizedBox(
                height: 20.0,
              ),
              defaultButton(
                text: 'ReGIster',
                function: () {
                  print(emailController.text);
                  print(passwordController.text);
                },
              ),
              SizedBox(
                height: 10.0,
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    'Don\'t have an account?',
                  ),
                  TextButton(
                    onPressed: () {},
                    child: Text(
                      'Register Now',
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    ),
  ),
);
}

Widget defaultButton({
double width = double.infinity,
Color background = Colors.blue,
bool isUpperCase = true,
double radius = 10.0,
required Function function,
required String text,
}) =>
  Container(
    width: width,
    height: 50.0,
    child: MaterialButton(
      onPressed: () {
        function();
      },
      child: Text(
        isUpperCase ? text.toUpperCase() : text,
        style: TextStyle(
          color: Colors.white,
        ),
      ),
    ),
    decoration: BoxDecoration(
      borderRadius: BorderRadius.circular(
        radius,
      ),
      color: background,
    ),
  );
}

Widget defaultFormField({
required TextEditingController controller,
required TextInputType type,
Function? onSubmit,
Function? onChange,
bool isPassword = false,
required String? Function(String?)? validate,
required String label,
required IconData prefix,
IconData? suffix,
Function? suffixPressed,
}) =>
  TextFormField(
    controller: controller,
    keyboardType: type,
    obscureText: isPassword,
    onFieldSubmitted: (s) {
      onSubmit!(s);
    },
    onChanged: (s) {
      onChange!(s);
    },
    validator: validate,
    decoration: InputDecoration(
      labelText: label,
      prefixIcon: Icon(
        prefix,
      ),
      suffixIcon: suffix != null
          ? IconButton(
              onPressed: () {
                suffixPressed!();
              },
              icon: Icon(
                suffix,
              ),
            )
          : null,
      border: OutlineInputBorder(),
    ),
  );

enter image description here

关于具有零安全性的 flutter 表单验证器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69118795/

相关文章:

安卓网络服务认证

dart - 用flutter无法创建哪些应用程序?

android - 在 Flutter 中使用新版本更新( native )android 应用程序,同时保留数据库

flutter - 有 ChangeNotifierList 吗?

image - 如何在 Dart/Flutter 中读取本地镜像文件的字节数?

github - 如何设置 dart.yml 以使用 build_runner 运行测试

ios - Flutter firebase消息传递,ios应用程序未收到 token

java - 在执行需要身份验证的http调用时如何解决循环依赖场景?

java - Jboss登录并重定向到正确的url

android - 改进 ListView of Rows 的整体布局