如何在 api 调用颤动期间处理空安全?

how to handle null safety during api call flutter?

我正在尝试执行一个 API 调用,但我遇到了一个错误,必须分配空安全变量。

这是我的代码

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

出现异常

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)

有什么解决办法可以解决这个问题

试过“?”没用。

Screenshot

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