Ad

How Can I Find The Length Of An Item From A List Based On Its Id In Flutter?

- 1 answer

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
...
Ad

Answer

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)

Ad
source: stackoverflow.com
Ad