无法无条件访问属性“isEmpty”,因为接收者可以为“null”

Nai*_*hul 6 flutter

我正在尝试向小部件添加验证器:

import 'package:flutter/material.dart';
    import 'package:flutter_app_1/utils/routes.dart';
    
    class LoginPage extends StatefulWidget {
      @override
      _LoginPageState createState() => _LoginPageState();
    }
    
    class _LoginPageState extends State<LoginPage> {
      String name = "";
      bool changeButton = false;
    
      final _formKey = GlobalKey<FormState>();
    
      moveToHome(BuildContext context) async {
        if (_formKey.currentState.validate()) {
          setState(() {
            changeButton = true;
          });
          await Future.delayed(Duration(seconds: 1));
          await Navigator.pushNamed(context, MyRoutes.homeRoute);
          setState(() {
            changeButton = false;
          });
        }
      }
    
      @override
      Widget build(BuildContext context) {
        return Material(
            color: Colors.white,
            child: SingleChildScrollView(
              child: Form(
                key: _formKey,
                child: Column(
                  children: [
                    Image.asset(
                      "assets/images/login_image.png",
                      fit: BoxFit.cover,
                      height: 500,
                    ),
                    SizedBox(
                      height: 20.0,
                    ),
                    Text(
                      "Welcome $name",
                      style: TextStyle(fontSize: 22, fontWeight: FontWeight.bold),
                    ),
                    SizedBox(
                      height: 28.0,
                    ),
                    Padding(
                      padding: const EdgeInsets.symmetric(
                          vertical: 16.0, horizontal: 32.0),
                      child: Column(
                        children: [
                          TextFormField(
                            decoration: InputDecoration(
                              hintText: "Enter User Name",
                              labelText: "Username",
                            ),
                            validator: (String? value) {
                              if (value != null && value.isEmpty) {
                                return "Username can't be empty";
                              }
    
                              return null;
                            },
                            onChanged: (value) {
                              name = value;
                              setState(() {});
                            },
                          ),
                          TextFormField(
                            obscureText: true,
                            decoration: InputDecoration(
                              hintText: "Enter password",
                              labelText: "Password",
                            ),
                            validator: (String? value) {
                              if (value != null && value.isEmpty) {
                                return "Password can't be empty";
                              }
    
                              return null;
                            },
                          ),
                          SizedBox(
                            height: 40.0,
                          ),
                          Material(
                            color: Colors.deepPurple,
                            borderRadius:
                                BorderRadius.circular(changeButton ? 50 : 8),
                            child: InkWell(
                              onTap: () => moveToHome(context),
                              child: AnimatedContainer(
                                duration: Duration(seconds: 1),
                                width: changeButton ? 50 : 150,
                                height: 50,
                                //color: Colors.deepPurple,
                                alignment: Alignment.center,
                                child: changeButton
                                    ? Icon(
                                        Icons.done,
                                        color: Colors.white,
                                      )
                                    : Text(
                                        "Login",
                                        style: TextStyle(
                                            color: Colors.white,
                                            fontWeight: FontWeight.bold,
                                            fontSize: 18),
                                      ),
                                // decoration: BoxDecoration(
                                //     //color: Colors.deepPurple,
                                //     // shape: changeButton
                                //     //     ? BoxShape.circle
                                //     //     : BoxShape.rectangle,
                                //     ),
                              ),
                            ),
                          ),
                          // ElevatedButton(
                          //     child: Text("Login"),
                          //     style: TextButton.styleFrom(minimumSize: Size(150, 40)),
                          //     onPressed: () {
                          //       Navigator.pushNamed(context, MyRoutes.homeRoute);
                          //     })
                        ],
                      ),
                    )
                  ],
                ),
              ),
            ));
      }
    }
Run Code Online (Sandbox Code Playgroud)

但我收到此错误:

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

Roh*_*ker 13

您需要使代码为 null 安全,为此您有几个选项,具体取决于您期望的值。

\n

如果您只需要一个值,则将String设为并更新验证器条件以添加after 。initialValue\'\'(value!.isEmpty)!value

\n

如果该值确实可以为 null,则添加一个测试以确保仅当该值为\xe2\x80\x99t null 时才访问成员,即如果initialValue设置为null,则需要更新验证器以检查 null。

\n
validator: (String? value) {                        \n  if (value != null && value.isEmpty) {\n    return "Username can\'t be empty";\n  }\n\n  return null;\n}\n
Run Code Online (Sandbox Code Playgroud)\n

如果您想了解有关 dart 中空安全的更多信息,请查看官方文档

\n


小智 9

您面临的错误来自空安全,您从验证器方法获取的值可以是空或字符串,因此您可能需要将代码更新为以下示例:

validator: (String? value) {                        
  if (value!.isEmpty) {
    return "Username cann't be empty";
  }

  return null;
}
Run Code Online (Sandbox Code Playgroud)

您可以在官方文档上了解更多关于空安全的信息:

https://dart.dev/null-safety