Home > Enterprise >  Error while Calculating and displaying total of Map Item in Flutter
Error while Calculating and displaying total of Map Item in Flutter

Time:03-15

I have a Map which stores an API response that I intend to use throughout my Application. Although, the API part works just as I expected, the trouble begins when I try displaying the total amount of all the objects. The total amount needs to be calculated in the following way:total = product_selling_price * quantity;. However, the logic that I have written throws the below error:

Class 'int' has no instance method '[]'.
Receiver: 0
Tried calling: []("product_selling_price")

The JSON response, the method that calculates the total and the widget from which the method is called are as follows. Also, I will mark the lines where the errors are pointed at.

The JSON response:

{
    "status": "success",
    "data": [
        {
            "cart_id": 18,
            "restaurant_id": "1",
            "product_id": "5",
            "restaurant_name": "City Club",
            "product_name": "Palak Paneer",
            "product_description": "Tasty silky gravy with goodness of palak",
            "product_image": "/public/assets/product/C6pGz101-42-17.jpg",
            "product_selling_price": "180",
            "product_status": "active",
            "product_quantity": "32",
            "quantity": "2"
        },
        {
            "cart_id": 17,
            "restaurant_id": "1",
            "product_id": "6",
            "restaurant_name": "City Club",
            "product_name": "Jersey Burger",
            "product_description": "Tasty yummy burgir. BURGIRRRRR",
            "product_image": "/public/assets/product/1Xf0sr01-43-20.jpg",
            "product_selling_price": "185",
            "product_status": "active",
            "product_quantity": "50",
            "quantity": "2"
        },
        {
            "cart_id": 16,
            "restaurant_id": "1",
            "product_id": "7",
            "restaurant_name": "City Club",
            "product_name": "Tibetan Soup",
            "product_description": "Healthy Soup from the mountains of Tibet",
            "product_image": "/public/assets/product/CgMBpm02-03-38.jpg",
            "product_selling_price": "120",
            "product_status": "active",
            "product_quantity": "24",
            "quantity": "2"
        }
    ]
}

The class with the method:

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

  Network network = Network();

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

  double deliveryCost = 40;
  double discountCost = 50;

  List<dynamic> get cartItemList {
    return [..._cartItemList];
  }

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

  Future<void> fetchCartItems() async {
    SharedPreferences localStorage = await SharedPreferences.getInstance();
    final url = Uri.parse(baseUrl   'api/auth/cart');
    final response = await http.get(url, headers: {
      'Authorization': 'Bearer ${localStorage.getString('token')}',
      'Accept': 'application/json'
    });
    Cart cartJson = cartFromJson(response.body);

    _cartItems = cartJson.toJson();
    print('Cart Item $_cartItems');
  }
  
  double get itemAmount {                  //The method in question
    double total = 0.0;
    total = _cartItems['data'].fold(      //The above error gets pointed from this line
        0,
        (price, value) =>
            price  
            (double.parse(price['product_selling_price']) *    //To This line, at price['product_selling_price']
                double.parse(price['quantity'])));
    return total;
  }
}

The Model Class in case someone needs to take a look:

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,
  });

  final String status;
  final 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.quantity,
  });

  final int cartId;
  final String restaurantId;
  final String productId;
  final String restaurantName;
  final String productName;
  final String productDescription;
  final String productImage;
  final String productSellingPrice;
  final String productStatus;
  final String productQuantity;
  final 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"],
        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,
        "quantity": quantity,
      };
}

The widget from which the itemAmount getter is called:

class CartDetailScreen extends StatefulWidget {
  CartDetailScreenState createState() => CartDetailScreenState();
}

class CartDetailScreenState extends State<CartDetailScreen> {

  @override
  Widget build(BuildContext context) {
    ......

    // TODO: implement build
    return Scaffold(
        ......
        body: ListView(
          children: [
            ........
                        ),
                        Text(
                            '₹ ${Provider.of<CartItemProvider>(context).itemAmount   //This is where the itemAmount method is accessed from
                            }',
                            ........
                      ],
        ));
  }
}

I would like to know what I need to do to fix and get rid of this error.

CodePudding user response:

In your itemAmount function you are using the price variable, when you should be using the value variable.

double get itemAmount {
  double total = 0.0;
  total = _cartItems['data'].fold(
      0,
      (price, value) =>
          price  
          (double.parse(value['product_selling_price']) * // use value not price
              double.parse(value['quantity']))); // use value not price
  return total;
}

CodePudding user response:

fold function is a reducer, first argument (you name it price) is the precedent value so it is an int not an array of int and second value (you name it value) is the current value.

So you can't use price[...] if current value is an array use value[...]

https://api.dart.dev/stable/1.10.1/dart-core/List/fold.html

Your code should be like this:

double get itemAmount {
  double total = 0.0;
  total = _cartItems['data'].fold(
      0,
      (price, value) =>
          price  
          (double.parse(value['product_selling_price']) * 
              double.parse(value['quantity']))); 
  return total;
}
  • Related