gpt4 book ai didi

list - 查询 map 列表的元素,并更新dart中的一个元素

转载 作者:行者123 更新时间:2023-12-03 04:48:37 25 4
gpt4 key购买 nike

我在 Dart 上有一个具有以下结构的 map

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

并且我需要增加id为asd2d21aa的List元素中的数量,该怎么做?因为它是购物车,并且产品数量大大增加。非常感谢你。

最佳答案

您可以在下面复制粘贴运行完整代码
您可以使用firstWhere并检查id
程式码片段

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

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

完整的代码
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),
),
);
}
}

关于list - 查询 map 列表的元素,并更新dart中的一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61808904/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com