Levan Lacroix
Levan Lacroix

Reputation: 25

query element of a list of maps, and update one element in dart

I have a map on Dart with the following structure

[
  {
   "id": 'asdasy21dh',
    "price": 23,
     "quantity": 2
  },
 {
   "id": 'asd2d21aa',
    "price": 43,
     "quantity": 1
  },
]

and I need to increase the amount of quantity in element of the List whit the id: asd2d21aa, how can I do this? since it is a shopping cart and the amount of products increases considerably. Thank you very much.

Upvotes: 0

Views: 3004

Answers (1)

chunhunghan
chunhunghan

Reputation: 54427

You can copy paste run full code below
You can use firstWhere and check id

code snippet

var target = cartList.firstWhere((item) => item["id"] == 'asd2d21aa');
if (target != null) {
    target["quantity"] = target["quantity"] + 1;
}

output

I/flutter (17317): {id: asd2d21aa, price: 43, quantity: 2}

full code

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  List<Map> cartList = [
    {"id": 'asdasy21dh', "price": 23, "quantity": 2},
    {"id": 'asd2d21aa', "price": 43, "quantity": 1},
  ];

  void _incrementCounter() {
    var target = cartList.firstWhere((item) => item["id"] == 'asd2d21aa');
    if (target != null) {
      target["quantity"] = target["quantity"] + 1;
    }
    print(cartList[1].toString());

    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

Upvotes: 3

Related Questions