对Flutter中的JSON数据求和



我来自web背景,我试图学习扑动,我正在建立一个购物车,我想根据用户在购物车中所拥有的东西来总结所有的价格,我使用PHP后端。下面是我获取数据库

的方法
final String apiURL = 'mydomain/fetchcart.php';
Future<List<ProductData>> fetchcart() async {
var data = {'id': int.parse(id)};
var response = await http.post(apiURL, body: json.encode(data));
if (response.statusCode == 200) {
final items = json.decode(response.body).cast<Map<String, dynamic>>();
List<ProductData> studentList = items.map<ProductData>((json) {
return ProductData.fromJson(json);
}).toList();
return studentList;
} else {
throw Exception('Failed to load data from Server.');
}
}

我使用一个futurebuilder传递它到一个小部件,但我想要和项目价格

FutureBuilder<List<ProductData>>(
future: fetchcart(),
builder: (context, snapshot) {
if (!snapshot.hasData)
return Center(child: CircularProgressIndicator());
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, int index) {
return cartItems(
snapshot.data[index].pid,
snapshot.data[index].pName,
snapshot.data[index].pSellingPrice,
snapshot.data[index].pImage);
},
);
}),

假设pSellingPrice是价格,在从将来的构建器返回studentList之前,使用foreach循环来获得总数。

首先在fetchcart()之外以合适的数据类型声明一个变量。我将使用double。

double total = 0;

在列表生成之后,

studentList.forEach((val){
total += val.pSellingPrice;
});

你可能需要调用setState取决于你的Ui。

最新更新