当前位置: 首页 > 知识库问答 >
问题:

错误:flutter/lib/ui/ui_dart_state.cc(177)未处理的异常:NoSuch方法错误:getter长度被称为空

戈博易
2023-03-14

我正在尝试用flatter和laravelapi构建一个应用程序。在我开始实现登录功能之前,一切都很顺利。我收到此错误[error:flatter/lib/ui/ui\u dart\u state.cc(177)]未处理的异常:NoSuchMethodError:对null调用了getter“length”

    var _userService = UserService();
    var registeredUser = await _userService.login(user);
    var result = json.decode(registeredUser.body);
    print(result);
    if(result['success']['result']== true){
      SharedPreferences _prefs = await SharedPreferences.getInstance();
      _prefs.setInt('userId', result['success']['user']['id']);
      _prefs.setString('userName', result['success']['user']['name']);
      _prefs.setString('userPhone', result['success']['user']['phone']);
      _prefs.setString('userEmail', result['success']['user']['email']);
      _prefs.setString('token', result['success']['token']);
      // Timer(Duration(seconds: 2), () {
      //   Navigator.pop(context);
      //   Navigator.popAndPushNamed(context, DashboardScreen.id);
      // });
      Navigator.push(
          context, MaterialPageRoute(builder: (context) => HomeScreen()));
    }  else {
      displayToastMessage('Failed to login!', context);
    }
  }```

When I press `Login button` this is how I call the `login` function.
```onPressed: () {
          if(!emailTextEditingController.text
              .contains("@")) {
            displayToastMessage(
                "Not a valid email address", context);
          }
          else if(passwordTextEditingController.text.length < 6) {
            displayToastMessage(
                "Password must be at least 6 characters", context);
          }  else {
            var user = User();
            // user.name = nameTextEditingController.text;
            user.email = emailTextEditingController.text;
            // user.phone = phoneTextEditingController.text;
            user.password = passwordTextEditingController.text;
            _login(context, user);
          }
        },```

This is the UsersService Code for login
`login(User user) async {
    return await _repository.httpPost('login', user.toJson());
  }`

and `_repositpry` is the one sending request to the `api`
here is how it is implemented 
`  String _baseUrl = 'https://api.adikatour.com/api';
   httpPost(String api, data) async {
    return await http.post(_baseUrl + "/" + api, body: data);
  }`

and here is the api code for login
` public function login(){ 
        if(Auth::attempt(['email' => request('email'), 'password' => request('password')])){ 
            $user = Auth::user(); 
            $success['token'] =  $user->createToken('MyApp')->accessToken; 
            $success['name'] =  $user->name;
            $success['user'] =  $user;
            return response()->json(['success' => $success], $this->successStatus); 
        } 
        else{
            return response()->json(['error'=>'Unauthorised'], 401); 
        } 
    }`

can you please tell me why I am getting this error? thanks again!

共有2个答案

申屠恺
2023-03-14

最后,我解决了这个问题。这就是我如何构建我使用的模型

class User {
  int id;
  String name;
  String email;
  String phone;
  String password;

  toJson(){
    return {
      'id' : id.toString(),
      'name' : name,
      'email' : email,
      'phone' : phone,
      'password' : password,
    };
  }
}

但在登录功能中,只设置了电子邮件和密码。由于我的服务器不允许phonename字段为空值,因此我必须将这些字段转换为非空值。所以,我像这样转换了用户模型。然后就解决了。

class User {
  int id;
  String name;
  String email;
  String phone;
  String password;

  toJson(){
    return {
      'id' : id.toString(),
      'name' : name.toString(),
      'email' : email.toString(),
      'phone' : phone.toString(),
      'password' : password.toString(),
    };
  }
}

谢谢你们帮助我,我真的很感激。特别感谢@sajith lakmal

阎冠玉
2023-03-14

按下按钮试试这个:-

onPressed: () {
      if(!emailTextEditingController.text
          .contains("@")) {
        displayToastMessage(
            "Not a valid email address", context);
      }
      else if (passwordTextEditingController.text is String && ((passwordTextEditingController.text?.length) ?? 0) < 6) {
        displayToastMessage(
            "Password must be at least 6 characters", context);
      }
     else if (!(passwordTextEditingController.text is String)){
        displayToastMessage(
            "Password must not be empty", context);
    }
     else {
        var user = User();
        // user.name = nameTextEditingController.text;
        user.email = emailTextEditingController.text;
        // user.phone = phoneTextEditingController.text;
        user.password = passwordTextEditingController.text;
        _login(context, user);
      }
    },
 类似资料: