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
CodePudding user response:
I am assuming your totalPrice is in a stateful widget?
I would make a function that takes the snapshot data and calculates the total price. After that updating the totalPrice. This allows you to keep the ListviewBuilder as it is.
Most importantly, don't forget to use setState(() => {totalPrice = <calculated>});. This notifies the widget of the change.
Additionally, this ensures your totalPrice is accurate since the ListBuilder only builds items that are currently being rendered on the screen.
CodePudding user response:
if (snapshot.hasData) {
final list = snapshot.data;
var totalPrice = list.map((e) => e[price]).toList()
.reduce((value, element) => value element));
}
CodePudding user response:
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(),);
},);
