Home > Software design >  How to fix this http request? Flutter/Dart
How to fix this http request? Flutter/Dart

Time:10-08

I am making a request but i have the following error:

I am making a request but i have the following error:

I am making a request but i have the following error:

Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List<dynamic>' in type cast

Here is my print:

{"firstName":"Georgee","lastName":"Contructed","userID":256,"month":8,"year":2022,"cardBills":[{"serial":"281929282881","value":4.8150,"vat":1.1556,"total":5.9706,"energy":0},{"serial":"281929282881","value":1.0567,"vat":0.2536,"total":1.3103,"energy":0}],"cardBillsTotal":[{"serial":"281929282881","value":5.8717,"vat":1.4092,"total":7.2809,"energy":0}]}

Here is my Class:

class YearBill {
  final String firstName;
  final String lastName;
  final int userID;
  final int month;
  final int year;
  const YearBill({
    required this.firstName,
    required this.lastName,
    required this.userID,
    required this.month,
    required this.year
  });
  factory YearBill.fromJson(Map<String, dynamic> json) {
    return YearBill(
      firstName: json['firstName'] as String,
      lastName: json['lastName'] as String,
      userID: json['userID']as int,
      month: json['month']as int,
      year: json['year']as int,
    );
  }
}

Here is my code:

List<YearBill> parsebills(String responseBody) {
    final parsedd = jsonDecode(responseBody).cast<Map<String, dynamic>>();

    return parsedd.map<YearBill>((json) => YearBill.fromJson(json)).toList();
  }

Future<List<YearBill>> fetchbills() async {
    String? token = await this.storage.read(key: "token");
    Map<String, String> headers = {
      "Content-Type": "application/json",
      "Accept": "application/json",
      "Authorization": "Bearer "   (token ?? ""),
    };
    final response = await http.get(Uri.parse(this.serverIP   ':'   this.serverPort   '/user/contractedChargeTransactions?month=8&year=2022'), headers: headers);


    print(response.body);
    cardclient = jsonDecode(response.body) as List;
    var results = cardclient.map((e) => YearBill.fromJson(e)).toList();
    print(results[0].month);
    return cardclient.map((e) => YearBill.fromJson(e)).toList();
  }

CodePudding user response:

The issue is with the response, your API returns a single object

{
  "firstName": "Georgee",
  "lastName": "Contructed",
  "userID": 256,
  "month": 8,
  "year": 2022,
  "cardBills": [{...

so if you want to get the user bills you should change

cardclient = jsonDecode(response.body) as List;
//TO
cardclient = jsonDecode(response.body)['cardBills'];

or if the API should return the bills for a multiple users then it should return a list of users with their bills and parse 'em the same way (the line written above)

  • Related