Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
274 views
in Technique[技术] by (71.8m points)

Sum JSON data in Flutter

I am from a web background and am trying to learn flutter, I am building a cart and I will like to sum all the price based on what the user has in the cart, am using a PHP backend. Below is my method that fetches the database

    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.');
   }
 }

Am using a futurebuilder to pass it to a widget, but I to want sum the item price

        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);
                  },
                );
              }),
question from:https://stackoverflow.com/questions/65907850/sum-json-data-in-flutter

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Assuming the pSellingPrice is the price, before returning the studentList from your future builder use a foreach loop to get the total.

first declare a variable outside the fetchcart() in a suitable data type. I will use a double.

double total = 0;

after List Generation,

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

you may need to call setState dependeing on your Ui.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...