Search code examples
apiflutterdartnullresponse

How to set 0 or null value from api to Model class in Flutter


I am calling an api with mixed values. Some value return 0 and others return int. But when I am calling that api, I am getting this error:

The getter 'actualTotalFee' was called on null.
Receiver: null
Tried calling: actualTotalFee

My api response is:

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

My api calling method:

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

My Model call:

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'],
    );
  }
}

Because of some response like "actual_total_fee", "per_semester_fee" etc returns 0 value, my api response method is failing.

Is there any way to run the api method or set 0 value to my model class?


Solution

  • in your model

      actualTotalFee: json['actual_total_fee'] ?? 0,
    

    in your call

    AccountSummeryObj?.actualTotalFee ?? 0