Home > database >  Converting a map into list of objects in flutter
Converting a map into list of objects in flutter

Time:03-14

I'm pretty new to Flutter and still struggling to understand a few things. My objective right now is to place map objects inside a list the logic for which that I've written hasn't been kind. I would therefore need suggestions as to how this can be achieved. The code I've written by far is below:

class CartItemProvider with ChangeNotifier {
  Map<String, dynamic> _cartItems = {};
  var _cartItemList = [];
  List<dynamic> _individualItems = [];

  Network network = Network();

  String baseUrl = 'https://achievexsolutions.in/current_work/eatiano/';

  double deliveryCost = 40;
  double discountCost = 50;

  Map<String, dynamic> get cartItems {
    return {..._cartItems};
  }

  Future<void> fetchCartItems() async {
    final url = Uri.parse(baseUrl   'api/auth/cart');
    final response = await http.get(url, headers: {
      'Authorization': 'Bearer ${network.getToken()}',
      'Accept': 'application/json'
    });
    Cart cartJson = cartFromJson(response.body);
    _cartItems = cartJson.toJson();
    _cartItems.forEach((key, values) => _cartItemList.add(values['data'])); 
    print(_cartItems);
  }
}

The error that I get says Unhandled Exception: NoSuchMethodError: The method 'map' was called on null.

{
    "status": "success",
    "data": [
        {
            "cart_id": 9,
            "restaurant_id": "6",
            "product_id": "8",
            "restaurant_name": "Mocambo",
            "product_name": "Kaju Paneer",
            "product_description": "Tasty yummy paneer gravy dish",
            "product_image": "/public/assets/product/lgml5L03-19-41.jpg",
            "product_selling_price": "320",
            "product_status": "active",
            "product_quantity": "41",
            "product_rating": null,
            "product_rating_count": null,
            "product_sell_count": null,
            "quantity": "1"
        }
    ]
}

I would like to store the objects in the list named data which is my main priority. The model class for the above response is below:

import 'package:meta/meta.dart';
import 'dart:convert';

Cart cartFromJson(String str) => Cart.fromJson(json.decode(str));

String cartToJson(Cart data) => json.encode(data.toJson());

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

  String status;
  List<Datum> data;

  factory Cart.fromJson(Map<String, dynamic> json) => Cart(
        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.cartId,
    required this.restaurantId,
    required this.productId,
    required this.restaurantName,
    required this.productName,
    required this.productDescription,
    required this.productImage,
    required this.productSellingPrice,
    required this.productStatus,
    required this.productQuantity,
    required this.productRating,
    required this.productRatingCount,
    required this.productSellCount,
    required this.quantity,
  });

  int cartId;
  String restaurantId;
  String productId;
  String restaurantName;
  String productName;
  String productDescription;
  String productImage;
  String productSellingPrice;
  String productStatus;
  String productQuantity;
  dynamic productRating;
  dynamic productRatingCount;
  dynamic productSellCount;
  String quantity;

  factory Datum.fromJson(Map<String, dynamic> json) => Datum(
        cartId: json["cart_id"],
        restaurantId: json["restaurant_id"],
        productId: json["product_id"],
        restaurantName: json["restaurant_name"],
        productName: json["product_name"],
        productDescription: json["product_description"],
        productImage: json["product_image"],
        productSellingPrice: json["product_selling_price"],
        productStatus: json["product_status"],
        productQuantity: json["product_quantity"],
        productRating: json["product_rating"],
        productRatingCount: json["product_rating_count"],
        productSellCount: json["product_sell_count"],
        quantity: json["quantity"],
      );

  Map<String, dynamic> toJson() => {
        "cart_id": cartId,
        "restaurant_id": restaurantId,
        "product_id": productId,
        "restaurant_name": restaurantName,
        "product_name": productName,
        "product_description": productDescription,
        "product_image": productImage,
        "product_selling_price": productSellingPrice,
        "product_status": productStatus,
        "product_quantity": productQuantity,
        "product_rating": productRating,
        "product_rating_count": productRatingCount,
        "product_sell_count": productSellCount,
        "quantity": quantity,
      };
}

CodePudding user response:

This three cases are likely the cause of your problem:

        "product_rating": null,
        "product_rating_count": null,
        "product_sell_count": null,

because in your function below

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

you're calling .map on a null object, hence the error. You have to handle somehow the cases where json["data"] is null before calling any method on it. Is your code null-safe? That might help in cases like this because I think the IDE would warn you of such nullable cases (at least, Android Studio does).

  • Related