我正在调用一个具有混合值的api。一些值返回0,另一些返回int。但当我调用该api时,我会得到以下错误:
The getter 'actualTotalFee' was called on null.
Receiver: null
Tried calling: actualTotalFee
我的api响应是:
"summary": {
"said_fee": 0,
"nos": 11,
"currentPayable": 0,
"eximp-sem": 1,
"sum_of_tution_fee": 173875,
"common_scholarship": 0,
"actual_total_fee": 0,
"special_scholarship": 10000,
"per_semester_fee": 0,
"per_semester_fee_without_scholarship": 0,
"total_paid": 190000,
"total_current_due": -200000,
"Due_Up_to_April": -200000,
"total_due": -200000
}
我的api调用方法:
// Getting Accounts Summery
Future<AccountSummery> fetchAccountSummery(int userId) async {
final url =
Api.baseUrl + 'student_account_info_summary/$userId?token=$authToken';
try {
final response = await get(Uri.encodeFull(url));
final loadedItem = json.decode(response.body);
if (response.statusCode == 200) {
return AccountSummery.fromJson(loadedItem['summary']);
} else {
throw Exception('Error in getting account summery');
}
} catch (error) {
throw error;
}
}
我的模型调用:
class AccountSummery {
final int actualTotalFee;
final int specialScholarship;
final int perSemesterWithoutScholarship;
final int perSemesterFee;
final int totalPaid;
final double totalCurrentDue;
final int totalDue;
AccountSummery(
{
this.actualTotalFee,
this.specialScholarship,
this.perSemesterWithoutScholarship,
this.perSemesterFee,
this.totalPaid,
this.totalCurrentDue,
this.totalDue
});
factory AccountSummery.fromJson(Map<String, dynamic> json) {
return AccountSummery(
actualTotalFee: json['actual_total_fee'],
specialScholarship: json['special_scholarship'],
perSemesterWithoutScholarship: json['per_semester_fee_without_scholarship'],
perSemesterFee: json['per_semester_fee'],
totalPaid: json['total_paid'],
totalCurrentDue: json['total_current_due'],
totalDue: json['total_due'],
);
}
}
因为一些回应,比如";actual_total_ feee"per_semester_fee";etc返回0值,我的api响应方法失败。
有什么方法可以运行api方法或为我的模型类设置0值吗?
在您的模型中
actualTotalFee: json['actual_total_fee'] ?? 0,
在您的呼叫
AccountSummeryObj?.actualTotalFee ?? 0
您可以通过两种方式实现:
-
actualTotalFee: json['actual_total_fee'] ?? 0
-
actualTotalFee: json['actual_total_fee'] !=null ? json['actual_total_fee'] : 0
如果API为空,则使用此选项将默认值设置为0:
actualTotalFee: json['actual_total_fee'] ?? 0,