The body might complete normally, causing 'null' to be returned, but the return type is a potentially non-nullable type.. json flutter

Issue

class CatalogModel {
  static var items = [
    Item(
        id: 1,
        name: "iPhone 12 Pro",
        desc: "Apple iPhone 12th generation",
        price: 999,
        color: "#33505a",
        image:
            "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRISJ6msIu4AU9_M9ZnJVQVFmfuhfyJjEtbUm3ZK11_8IV9TV25-1uM5wHjiFNwKy99w0mR5Hk&usqp=CAc")
  ];
}

class Item {
  final int id;
  final String name;
  final String desc;
  final num price;
  final String color;
  final String image;

  Item(
      {required this.id,
      required this.name,
      required this.desc,
      required this.price,
      required this.color,
      required this.image});

      factory Item.fromMap(Map<String,dynamic> map){
        Item(
          id: map["id"],
          name: map["name"],
          desc: map["desc"],
          price: map["price"],
          color: map["color"],
          image: map["image"],
        );
      }

      toMap()=>{
        "id":id,
        "name":name,
        "desc":desc,
        "price":price,
        "color":color,
        "image":image,
      }
}

I am getting this error….The body might complete normally, causing ‘null’ to be returned, but the return type, ‘Item’, is a potentially non-nullable type.
Try adding either a return or a throw statement at the end

Solution

You created a factory that doesn’t return anything when you should return an Item class.

You can update you factory method with the following code:

 factory Item.fromMap(Map<String,dynamic> map) => Item(
          id: map["id"],
          name: map["name"],
          desc: map["desc"],
          price: map["price"],
          color: map["color"],
          image: map["image"],
        );
      
    ```

Answered By – BLKKKBVSIK

Answer Checked By – Mary Flores (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *