Home > front end >  Unhandled Exception: type 'Welcome' is not a subtype of type 'Map<String, dynamic&
Unhandled Exception: type 'Welcome' is not a subtype of type 'Map<String, dynamic&

Time:03-02

I'm pretty new to Flutter and struggling to parse a JSON data of type Map which is as below. Everytime I try fetching the data and storing it, I keep getting Unhandled Exception: type 'Welcome' is not a subtype of type 'Map<String, dynamic>' in type cast

{
    "status": "success",
    "data": [
        {
            "product_id": 10,
            "restaurant_name": "new restaurant5",
            "product_name": "Test Product new 2",
            "product_desciption": "A cool new test product new 2",
            "product_image": null,
            "product_selling_price": "450",
            "product_status": "active",
            "product_quantity": "500",
            "product_rating": null,
            "product_rating_count": null,
            "product_sell_count": null
        },
        {
            "product_id": 9,
            "restaurant_name": "new restaurant5",
            "product_name": "Test Product new 1",
            "product_desciption": "A cool new test product new",
            "product_image": null,
            "product_selling_price": "400",
            "product_status": "active",
            "product_quantity": "100",
            "product_rating": null,
            "product_rating_count": null,
            "product_sell_count": null
        },
        {
            "product_id": 8,
            "restaurant_name": "new restaurant5",
            "product_name": "Test Product new",
            "product_desciption": "A cool new test product new",
            "product_image": null,
            "product_selling_price": "350",
            "product_status": "active",
            "product_quantity": "1000",
            "product_rating": null,
            "product_rating_count": null,
            "product_sell_count": null
        },
}

I have used used Quicktype.io to generate the Model Class from JSON to dart which is as follows:

Welcome welcomeFromJson(String str) => Welcome.fromJson(json.decode(str));

String welcomeToJson(Welcome data) => json.encode(data.toJson());

class Welcome {
  Welcome({
    required this.status,
    required this.data,
  });

  String status;
  List<Datum> data;

  factory Welcome.fromJson(Map<String, dynamic> json) => Welcome(
        status: json["status"],
        data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
      );

  Map<String, dynamic> toJson() => {
        "status": status,
        "data": List<dynamic>.from(data.map((x) => x.toJson())),
      };
}

class Datum {
  Datum({
    required this.productId,
    required this.restaurantName,
    required this.productName,
    required this.productDesciption,
    required this.productImage,
    required this.productSellingPrice,
    required this.productStatus,
    required this.productQuantity,
    required this.productRating,
    required this.productRatingCount,
    required this.productSellCount,
  });

  int productId;
  RestaurantName? restaurantName;
  String productName;
  String productDesciption;
  String productImage;
  String productSellingPrice;
  ProductStatus? productStatus;
  String productQuantity;
  dynamic productRating;
  dynamic productRatingCount;
  dynamic productSellCount;

  factory Datum.fromJson(Map<String, dynamic> json) => Datum(
        productId: json["product_id"],
        restaurantName: restaurantNameValues.map[json["restaurant_name"]],
        productName: json["product_name"],
        productDesciption: json["product_desciption"],
        productImage:
            json["product_image"] == null ? null : json["product_image"],
        productSellingPrice: json["product_selling_price"],
        productStatus: productStatusValues.map[json["product_status"]],
        productQuantity:
            json["product_quantity"] == null ? null : json["product_quantity"],
        productRating: json["product_rating"],
        productRatingCount: json["product_rating_count"],
        productSellCount: json["product_sell_count"],
      );

  Map<String, dynamic> toJson() => {
        "product_id": productId,
        "restaurant_name": restaurantNameValues.reverse![restaurantName],
        "product_name": productName,
        "product_desciption": productDesciption,
        "product_image": productImage == null ? null : productImage,
        "product_selling_price": productSellingPrice,
        "product_status": productStatusValues.reverse![productStatus],
        "product_quantity": productQuantity == null ? null : productQuantity,
        "product_rating": productRating,
        "product_rating_count": productRatingCount,
        "product_sell_count": productSellCount,
      };
}

enum ProductStatus { ACTIVE }

final productStatusValues = EnumValues({"active": ProductStatus.ACTIVE});

enum RestaurantName { NEW_RESTAURANT5, RESTAURANR_2 }

final restaurantNameValues = EnumValues({
  "new restaurant5": RestaurantName.NEW_RESTAURANT5,
  "Restauranr 2": RestaurantName.RESTAURANR_2
});

class EnumValues<T> {
  Map<String, T> map;
  Map<T, String>? reverseMap;

  EnumValues(this.map);

  Map<T, String>? get reverse {
    if (reverseMap == null) {
      reverseMap = map.map((k, v) => new MapEntry(v, k));
    }
    return reverseMap;
  }
}

This is the class from which I'm making the API Call:

import 'package:http/http.dart' as http;
import './providerModel.dart';

class ApiProvider with ChangeNotifier {
  Map<String, dynamic> _result = {};

  Future<void> fetchProduct() async {
    final url = Uri.https('achievexsolutions.in', '/etiano/api/all_products');
    final response = await http.get(url);
    print(response);
    Welcome data = welcomeFromJson(response.body);     //This is probably where the error gets thrown`enter code here`
    print(data);
    _result = data as Map<String, dynamic>;
    print(_result);
  }
}

CodePudding user response:

You are currently assigning an entire model class to your _result variable. What you have to do is, convert the model to a Map object and then assign it to the _result variable like so:

Welcome data = welcomeFromJson(response.body);  
    print(data);
    _result = data.toJson();
    print(_result);
  • Related