0

am trying to do an API call where am getting an error to hangle null safety variable must be assigned.

here is my code

Future<LoginResponseModel> loginCustomer(
      String username, String password) async {
    LoginResponseModel model;

    try {
      var response = await Dio().post(Config.tokenURL,
          data: {
            "username": username,
            "password": password,
          },
          options: Options(headers: {
            HttpHeaders.contentTypeHeader: "application/x-www-form-urlencoded",
          }));

      if (response.statusCode == 200) {
        model = LoginResponseModel.fromJson(response.data);
      }
    } on DioError catch (e) {
      print(e.message);
    }
    return model;
  }

exception am getting

The non-nullable local variable 'model' must be assigned before it can be used. Try giving it an initializer expression, or ensure that it's assigned on every execution path.dart (not_assigned_potentially_non_nullable_local_variable)

is there any solution to handle this

tried "?" it's not working.

Screenshot

naveen
  • 49
  • 1
  • 6
  • You don't initialize `model` along all possible code paths. You either must initialize it along all code paths (such as if `response.statusCode != 200` or if a `DioError` is caught) or must make `model` nullable *and* must fix the return type to match. – jamesdlin Aug 24 '21 at 09:42

1 Answers1

0
  Future<LoginResponseModel?> loginCustomer(
      String username, String password) async {
    LoginResponseModel? model;

    try {
      var response = await Dio().post(Config.tokenURL,
          data: {
            "username": username,
            "password": password,
          },
          options: Options(headers: {
            HttpHeaders.contentTypeHeader: "application/x-www-form-urlencoded",
          }));

      if (response.statusCode == 200) {
        model = LoginResponseModel.fromJson(response.data);
      }
    } on DioError catch (e) {
      print(e.message);
    }
    return model;
  }
Mozes Ong
  • 1,204
  • 1
  • 11
  • 20