Home > Software design >  The body might complete normally, causing 'null' to be returned, but the return type is a
The body might complete normally, causing 'null' to be returned, but the return type is a

Time:03-28

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

CodePudding user response:

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

CodePudding user response:

I found two fixes:

  • Add return keyword in Item.fromMap

    return Item(
      id: map["id"],
      name: map["name"],
      ...
    );
    
  • Colon missing at the end of toMap

  • Related