Home > Software design >  Model that fetch data from 2 different json, how to handle it?
Model that fetch data from 2 different json, how to handle it?

Time:08-12

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>.

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

CodePudding user response:

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

  • Related