Rodrigues silva
Rodrigues silva

Reputation: 87

type 'null' is not a subtype of type 'map string dynamic ' flutter

I'm trying to use the API in my application it works normally, but when JSON gets null the app doesn't work.

works normally:

{
   "product":{
      "description_1":"Lorem Ipsum is simply dummy text of the printing and typesetting industry.",
      "description_2":"Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old.",
      "description_3":"There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteratenter code hereion in some form",

   }
}

Error: "type 'null' is not a subtype of type 'map string dynamic ' ":

{ "product":null }

Class:

class Store {
  Store({
    required this.product,
  });

  Product product;

  factory Store.fromJson(Map<String, dynamic> json) => Store(
        product: Product.fromJson(json["product"]),
      );

  Map<String, dynamic> toJson() => {
        "product": product.toJson(),
      };
}

class Product {
  Product({
    required this.description1,
    required this.description2,
    required this.description3,
  });

  String description1;
  String description2;
  String description3;

  factory Product.fromJson(Map<String, dynamic> json) => Product(
        description1: json["description_1"] ?? "",
        description2: json["description_2"] ?? "",
        description3: json["description_3"] ?? "",
      );

  Map<String, dynamic> toJson() => {
        "description_1": description1,
        "description_2": description2,
        "description_3": description3,
      };
}

Upvotes: 1

Views: 1613

Answers (1)

lepsch
lepsch

Reputation: 10319

If product can actually be null then Store needs to deal with it. Change the Store class product property to be nullable with ? symbol like the following:

class Store {
  Store({
    this.product,
  });

  Product? product;

  factory Store.fromJson(Map<String, dynamic> json) => Store(
        product: json["product"] != null 
            ? Product.fromJson(json["product"])
            : null,
      );

  Map<String, dynamic> toJson() => {
        "product": product?.toJson(),
      };
}

Upvotes: 2

Related Questions