How can I find the length of an item from a list based on its id in Flutter?

812

First of all I think you have a problem in the declaration of your variable.

This is how it should be declared like this with the type before:

Map<String, List<Map<String, String>>> product = {
    'basket': [
      {
        "product name": "apple",
        "product id": "1",
        "quantity": "2",
      },
      {
        "product name": "apple",
        "product id" : "1",
        "quantity" : "5",
      },
      {
        "product name": "orange",
        "product id" : "2",
        "quantity" : "10",
      }
    ]
  };

The second problem here is that you don't use correctly things I guess you're not needing a Map<String, List<Map<String, String>>> but a Map<String, Map<String, int>>

So you could have this for example:

Map<String, Map<String, int>> product = {
  'apple': {
    'id': 1,
    'quantity': 2,
  },
  'banana': {
    'id': 2,
    'quantity': 10,
  },
};

Now you have this it is easier to access an element of the Map because you access it by the name of the product.

Here I made you an example of use:

  Map<String, Map<String, int>> product = {
    'apple': {
      'id': 1,
      'quantity': 2,
    },
    'banana': {
      'id': 2,
      'quantity': 10,
    },
    'potato': {
      'id': 3,
    },
  };

  void addQuantityFromProductName({
    String productName = '',
    int quantity = 0
  }) {
    if (productName != '' && product.containsKey(productName))
      setState(() {
        (product[productName] as Map<String, int>).update(
          'quantity',
          (existingValue) => existingValue + quantity,
          ifAbsent: () => quantity
        );
      });
  }

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Container(
        child: ListView.builder(
          shrinkWrap: true,
          itemCount: product.length,
          itemBuilder: (BuildContext context, int i) {
            return ListTile(
              onTap: () => addQuantityFromProductName(
                productName: product.keys.elementAt(i),
                quantity: 10
              ),
              title: Text(
                product.keys.elementAt(i)
              ),
              trailing: Text(
                product.values.elementAt(i)['quantity'] == null ? "Undefined" :
                product.values.elementAt(i)['quantity'].toString()
              ),
            );
          }
        )
      )
    );
  }

So here in the example, when you will click on a ListTile you will add 10 quantity to the product name

before pressing

enter image description here

after pressing

enter image description here

You have here a notion of how to access and update an element or a value of a map of map (doubly map)

Share:
812
muhammed jasir
Author by

muhammed jasir

Updated on December 31, 2022

Comments

  • muhammed jasir
    muhammed jasir over 1 year

    I got a list List product=[];

    product=await dbHelper.getProducts();

    I was trying to build a cart with sqflite, I get a list such that the same product shows in different list tile, here's my code,

     product={[{ "product name" : "apple", "product id" : "1", "quantity" : "2",},{ "product name" : "apple", "product id" : "1", "quantity" : "5",},{ "product name" : "orange", "product id" : "2", "quantity" : "10",}]}
    
    ListView.builder(
              itemCount: product.length,
                itemBuilder: (c,i){
                return ListTile(
                  title:Text(product[i].product_varient_name.toString()),
                  subtitle: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(product[i].base_price),
                      Text("qty : "+product[i].varient_id),
                      Container(
                          height: 80,width: 80,
                          child: Image.network("https://v.3multi.qgrocer.in/public/" +product[i].varient_image.toString())),
    
                    ],
                  ),
                );
                }),
    

    Output is,

    01   Apple  5
    02   Apple  2
    03   orange 1
    ...
    
    • SARAN SURYA
      SARAN SURYA over 2 years
      Hi, So can you add a clear example of how a list will look like, with the data. Ex : List product = [x, y, z ...] It will be helpful for providing the answers.
    • muhammed jasir
      muhammed jasir over 2 years
      List is like product={[{ "product name" : "apple", "product id" : "1", "quantity" : "2",},{ "product name" : "apple", "product id" : "1", "quantity" : "5",},{ "product name" : "orange", "product id" : "2", "quantity" : "10",}]}
    • Da2ny
      Da2ny over 2 years
      Can you clarify your question, what do you want exactly ?
    • muhammed jasir
      muhammed jasir over 2 years
      as in cart , products shows like product and total quantity added, but in my case, if user added 3 apple to cart, my list get updates as {[{ "product name": "apple", "quantiy": "1", "product id": "1"},{ "product name": "apple", "quantiy": "1", "product id": "1"},{ "product name": "apple", "quantiy": "1", "product id": "1"}]}, like this, so i want show my cart like apple quantity 3