Issue
i am creating a app in which i need to show total price of the cart items: so i am getting data in json and returning that data in futurebuilder and accesing it like;
list[index]['price']
and intialize a variable for total :
double totalPrice = 0;
and adding values as follows:
FutureBuilder(
future: myFuture,
builder: (context, AsyncSnapshot snapshot) {
if (!snapshot.hasData) {
// still waiting for data to come
return Center(
child: CircularProgressIndicator(),
);
} else if (snapshot.hasData &&
snapshot.data.isEmpty) {
return Center(child: Text("No Products"));
;
} else {
if (snapshot.hasError) print(snapshot.error);
return snapshot.hasData
? ListView.builder(
itemCount: snapshot.data!.length,
itemBuilder: (BuildContext context, index) {
//below the code of adding price
List list = snapshot.data;
totalPrice = totalPrice + list[index]['price'];
print("this is the total:$totalPrice");
return Container(..My Ui..
):Center(child: Text("no data"));
}
}, //futurebuilder ends here
),
Padding(
padding: const EdgeInsets.all(16.0),
child: Text(
'Total :₹ $totalPrice', // showing total price here
style: TextStyle(
fontSize: 20,
color: darkGrey,
fontWeight: FontWeight.bold),
),
),
but this totalPrice always show 0
can someone tell me how to update this variable inside a build? Thanks in advance <3
Solution
Not try to do like this. Use these method..
FutureBuilder(builder: (context, snapshot) {
if(snapshot.hasData){
//Only run when you get data
final list = snapshot.data;
var totalPrice = list.map((e) => e[price]).toList()
.reduce((value, element) => value + element);
return ReturnYourWidget();
}
//Until you get data show the loader
return Center(child: CircularProgressIndicator(),);
},);
Answered By - Vishal_VE
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.