Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Model that fetch data from 2 different json, how to handle it?

I’m creating an app that shows a list of cryptocurrencies and when you tap on one it opens a detailed view page.
For the list I fetch basic info, and when the details view opens I want to fetch all the information I miss.

I’m using 2 different API calls, the first returns me a list of cryptos, and for the second one, I receive more information about one in particular.

I’m using the same model Crypto for both API calls, my issue is that in the first API call for the ‘item’ image I get the image as a String, in the detailed view I get a Map<String, String>.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

My question is if it’s possible to use the same Model or I should have two different models, like CrytoList, CryptoDetailed?

JSON 1 (detailed one):

{
   "id":"bitcoin",
   "symbol":"btc",
   "name":"Bitcoin",
   "image":{
      "thumb":"imageurl",
      "small":"imageurl",
      "large":"imageurl"
   }
}

JSON 2 (list one):

{
  [
   "id":"bitcoin",
   "symbol":"btc",
   "name":"Bitcoin",
   "image":"imageurl"
  ]
}

My model:

class Crypto {
  Crypto({
    required this.id,
    required this.symbol,
    required this.name,
    required this.image,
  });

  final String id;
  final String symbol;
  final String name;
  final Image? image;

  factory Crypto.fromJson(Map<String, dynamic> json) {
    return Crypto(
      id: json["id"] ?? "",
      symbol: json["symbol"] ?? "",
      name: json["name"] ?? "",
      image: json["image"] == null ? null : Image.fromJson(json["image"]),
  }
}

class Image {
  Image({
    required this.thumb,
    required this.small,
    required this.large,
  });

  late final String thumb;
  late final String small;
  late final String large;

  factory Image.fromJson(Map<String, dynamic> json) {
    return Image(
      thumb: json["thumb"] ?? "",
      small: json["small"] ?? "",
      large: json["large"] ?? "",
    );
  }
}

>Solution :

you can have image and detailImage both, and fill image (string) with first api and fill detailImage(Map) with the second one.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading