0

我正在尝试使用颤振和 laravel api 构建应用程序。login在我开始实现该功能之前一切都很好。我收到这个错误[ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: NoSuchMethodError: The getter 'length' was called on null. 你能告诉我我的代码有什么问题吗?万一我犯了一个愚蠢的错误,请不要生气,我才刚刚开始编程。非常感谢!登录功能代码

    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!
4

2 回答 2

0

按下时试试这个: -

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);
      }
    },
于 2021-03-12T05:51:36.393 回答
0

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

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,
    };
  }
}

但是在 _login 函数中,只设置了电子邮件和密码。由于我的服务器不允许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

于 2021-03-13T08:48:18.603 回答