skip to Main Content

This is my function in a Flutter app to calculate the final price of the product by multiplying the product price and product quantity from the list

int calci() {
  int totalPrice = 0;
  for (int i = 0; i < cartitem.length; i++) {
    int price = int.parse(cartitem[i][1]);
    int quantity = int.parse(cartitem[i][4]);
    totalPrice += price * quantity;
  }
  return totalPrice;
}

and here is the code where I am displaying it

Text(
  '₹${calci().toString()}',
  style: const TextStyle(
    fontSize: 18,
    fontWeight: FontWeight.bold,
    color: Colors.white,
  ),
),

Now after running the app, this is giving me an error of typecasting I don’t know I tried a lot but was unable to resolve it.

Expected a value of type 'String', but got one of type 'int'

2

Answers


  1. Int.parse needs a string to parse. The cart item is probably an integer. You can try

    int.parse(cartitem[i][1].toString())
    
    Login or Signup to reply.
  2. Make sure that your cartitem List does not have elements of dynamic types, like:

    List cartitem = [
      ["Apple", 100, 1, 100, 1],
      ["Banana", "50", "1", "50", "1"],
    ];
    

    or

    List cartitem = [
      ["Grapes", "120", "1", 120, 4 ],
      ["Mango", "150", "1", 150,  4 ],
    ];
    

    Declare cartitem as:

    List<String> cartitem = {
      ["Banana", "50", "1", "50", "1"],
    ];
    

    Although I would suggest using a list of objects of type item, something like:

    example:

    import 'package:flutter/material.dart';
    
    void main() => runApp(const MyApp());
    
    class MyApp extends StatelessWidget {
      const MyApp({super.key});
    
      @override
      Widget build(BuildContext context) {
        List cartitem = [
          Item(name: "Apple", price: 100, quantity: 1),
          Item(name: "Banana", price: 50, quantity: 1),
          Item(name: "Orange", price: 80, quantity: 1),
          Item(name: "Grapes", price: 120, quantity: 1),
        ];
    
        num calci() {
          num totalPrice = 0;
          for (var item in cartitem) {
            totalPrice += item.price * item.quantity;
          }
          return totalPrice;
        }
    
        return MaterialApp(
          home: Scaffold(
            body: Center(
              child: Text(
                '₹${calci().toString()}',
                style: const TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                  color: Colors.black,
                ),
              ),
            ),
          ),
        );
      }
    }
    
    class Item {
      Item({required this.name, required this.price, required this.quantity});
      final String name;
      final double price;
      final int quantity;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search