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

时间:2021-06-26 11:03:07

标签: 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);
                          //     })
                        ],
                      ),
                    )
                  ],
                ),
              ),
            ));
      }
    }

大家好, 我正在尝试将验证器添加到小部件,但出现此错误,请帮忙。来解决这个错误。

错误:

The method 'validate' can't be unconditionally invoked because the receiver can be 'null'. Try making the call conditional (using '?.') or adding a null check to the target ('!')

我尝试替换提供的代码,但仍然出现错误。请查收。

第二个错误:

The method 'validate' can't be unconditionally invoked because the receiver can be 'null'. Try making the call conditional (using '?.') or adding a null check to the target ('!')

我尝试替换提供的代码,但仍然出现错误。请查收。

2 个答案:

答案 0 :(得分:1)

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

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

  return null;
}

您可以在官方文档中了解有关 null 安全的更多信息:

https://flutter.dev/docs/null-safety

答案 1 :(得分:1)

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

如果您只想要一个 String 值,那么将 initialValue 设置为 '' 并将验证器条件更新为 (value!.isEmpty) 在 {{1} 后添加一个 ! }}。

如果该值确实可以为空,则添加一个测试以确保仅当该值不为空时才访问成员,即如果value设置为initialValue,那么您将需要更新验证器以检查是否为空。

null

如果您想了解更多有关 dart 中的 null 安全性的信息,请查看 official docs