【问题标题】:Null Safety Issue in flutter颤振中的空安全问题
【发布时间】:2022-01-11 14:22:27
【问题描述】:
    if (_formKey.currentState.validate()) {
        setState(() {
          buttonChanged = false;
        });
      
    }

根据我的逻辑,上面的语句可以让我使用登录名和密码验证登录,但我不断收到错误

不能无条件地调用方法“validate”,因为接收者可以是“null”。 尝试使调用有条件(使用'?.')或向目标添加空检查('!')。

当我执行if (_formKey.currentState!.validate()) 错误消失但我的验证不起作用时,即使不应该登录也会发生。

请帮我解决这个问题,我是初学者,通过 youtube 学习 Flutter 应用程序开发。

这是我的全部代码


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

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

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

class _LoginPageState extends State<LoginPage> {
  bool buttonChanged = false;
  String name = "";
  final _formKey = GlobalKey<FormState>();

  moveToHome(BuildContext context) async {
    if (_formKey.currentState.validate()) {
      setState(() {
        buttonChanged = false;
      });
    }

    await Future.delayed(const Duration(seconds: 1));
    await Navigator.pushNamed(context, route.home);
    setState(() {
      buttonChanged = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      color: Colors.grey[500],
      child: Form(
        key: _formKey,
        child: Column(
          children: [
            const CircleAvatar(backgroundImage: AssetImage('images/login.jpg')),
            const SizedBox(height: 15.0),
            Text('Welcome $name',
                style: const TextStyle(
                    fontSize: 24.0, fontWeight: FontWeight.bold)),
            const SizedBox(height: 15.0),
            Padding(
                padding:
                    const EdgeInsets.symmetric(horizontal: 15, vertical: 32),
                child: Column(
                  children: [
                    TextFormField(
                        decoration: const InputDecoration(
                            hintText: 'Enter the username',
                            labelText: 'UserName:'),
                        onChanged: (value) {
                          name = value;
                          setState(() {});
                        },
                        validator: (value) {
                          if (value != null && value.isEmpty) {
                            return 'Please enter the username';
                          }

                          return null;
                        }),
                    TextFormField(
                        obscureText: true,
                        decoration: const InputDecoration(
                            hintText: 'Enter the password',
                            labelText: 'Password:'),
                        validator: (value) {
                          if (value != null && value.isEmpty) {
                            return 'Please enter the password';
                          } else if (value != null && value.length < 6) {
                            return 'Password must be atleast 6 characters';
                          } else {
                            return null;
                          }
                        }),
                    const SizedBox(height: 15.0),
                    Material(
                        borderRadius:
                            BorderRadius.circular(buttonChanged ? 50.0 : 10.0),
                        color: Colors.blue,
                        child: InkWell(
                          splashColor: Colors.red,
                          onTap: () => moveToHome(context),
                          child: AnimatedContainer(
                            duration: const Duration(seconds: 1),
                            width: buttonChanged ? 50 : 130,
                            height: 50,
                            alignment: Alignment.center,
                            child: buttonChanged
                                ? const Icon(Icons.done)
                                : const Text(
                                    'Login',
                                    style: TextStyle(
                                        color: Colors.white,
                                        fontWeight: FontWeight.bold,
                                        fontSize: 16),
                                  ),
                          ),
                        ))
                  ],
                ))
          ],
        ),
      ),
    );
  }
}





【问题讨论】:

    标签: flutter dart dart-null-safety


    【解决方案1】:

    您的validation logic 必须是:

    如果用户的输入无效,验证器函数会返回一个包含错误消息的字符串。如果没有错误,验证器必须返回 null。

    但是您在 validator 属性中使用了不正确的代码。以下代码:

    validator: (value) {
      if (value != null && value.isEmpty) {
        return 'Please enter the username';
      }
    
      return null;
    }),
    

    如果您没有将文本插入到TextFormField,将始终返回 null。所以,

    如果您的两个 TextFormField 都没有文本,_formKey.currentState!.validate() 将始终返回 true。

    要解决这个问题,修改代码如下:

    validator: (value) {
      if (value == null || value.isEmpty) {
        return 'Please enter the username';
      }
    
      return null;
    }),
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-26
      • 2021-10-22
      • 2020-12-25
      • 1970-01-01
      • 1970-01-01
      • 2021-09-22
      相关资源
      最近更新 更多