如何在构建中更改ui?颤动

  • 本文关键字:ui 颤动 构建 flutter dart
  • 更新时间 :
  • 英文 :


我正在创建一个应用程序,需要在其中显示购物车项目的总价:所以我在json中获取数据,并在futurebuilder中返回数据,然后像这样访问它;

list[index]['price']

并初始化total的变量:

double totalPrice=0;

并按如下方式添加值:

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),
),
),

但是这个总价总是显示0

有人能告诉我如何在构建中更新这个变量吗?提前感谢<3

不要这样做。使用以下方法。。

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(),);
},);

我假设您的totalPrice在一个有状态的小部件中?我会制作一个函数,获取快照数据并计算总价。之后更新CCD_ 2。这允许您保持ListviewBuilder的原样。

最重要的是,不要忘记使用setState(() => {totalPrice = <calculated>});。这会将更改通知小部件。

此外,这可以确保totalPrice的准确性,因为ListBuilder只构建当前在屏幕上呈现的项目。

if (snapshot.hasData) {
final list = snapshot.data;
var totalPrice = list.map((e) => e[price]).toList()
.reduce((value, element) => value + element));
}

最新更新