Home > Software engineering >  How to assign the non-nullable local variable 'user'
How to assign the non-nullable local variable 'user'

Time:01-20

How do I fix the following code?

The error is on the line : "return user" and is:

"The non-nullable local variable 'user' must be assigned before it can be used."

Future<UserLogin> fetchStaff(String pUserName, String pPassword) async {
  final response = await http
      .post(Uri.parse(Uri.encodeFull('$kBaseUrl/LoginService/CheckLogin')),
          headers: {'Content-Type': 'application/json', 'Accept': 'application/json'},
          body: '{ "pUser": "$pUserName", "pPassword": "$pPassword"}')
      .timeout(Duration(seconds: kTimeOutDuration));
  print('respose code = $response.statusCode');
  if (response.statusCode == 200) {
    // If the server did return a 200 OK response,then parse the JSON.
    return UserLogin.fromJson(json.decode(response.body));
  } else {
    // If the server did not return a 200 OK response, then throw an exception.
    //throw Exception('User or Password was incorrect.');

    globals.gblUserName = '';
    globals.gblPassword = '';
    UserLogin user;
    return user;
  }
}

CodePudding user response:

If you want to declare a nullabe variable, you should place ? after your type like this:

UserLogin? user;

and your future generic:

Future<UserLogin?> fetchStaff(String pUserName, String pPassword) async {
...
  •  Tags:  
  • Related