【发布时间】:2021-01-06 01:35:14
【问题描述】:
我有一个用户对象列表,他们保存用户数据并显示为 ListView。每个项目都有一个按钮,当我单击一个项目按钮时,我试图更新 ListView 中的特定项目。但我不能,我重新加载了完整的 ListView,如下所示......我想按顺序仅更新列表数据中的特定对象并更新这些按钮标题并根据付款ID将紫色更改为绿色。有没有办法只更新 ListView 中的一个项目而不必刷新整个列表?
ListView 是这样加载的:
FutureBuilder(
future: getInwardResidentList(param),
builder: (BuildContext context, AsyncSnapshot snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.waiting:{
return Container();}
case ConnectionState.active:{
break;}
case ConnectionState.done:{
if (snapshot.hasData) {
if (snapshot.data != null) {
if (snapshot.data.length > 0) {
return Container(
color: Colors.white70,
child: Scrollbar(
child: ListView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
physics: ScrollPhysics(),
padding: EdgeInsets.all(5),
itemCount: snapshot.data.length,
itemBuilder: (context, index) {
return generateColumn(item, index)
}),
),
);
}
}
}
}
}
return Container();
},
)
这是我的点击按钮代码
Widget generateColumn(InwardResidentModel item, int index) => Column(
children: <Widget>[
Row(
children: <Widget>[
...,
...,
Column(
children: <Widget>[
if (item.payment_status_id == "1")
MaterialButton(
onPressed: () {},
minWidth: 50,
height: 25,
padding: EdgeInsets.all(8),
child: Text("Paid ₹${item.amount}",
style: TextStyle(
color: Colors.green, fontSize: 13)),
),
if (item.payment_status_id != "1")
MaterialButton(
onPressed: () {
setState(() {
inwardResidentModelList[index] = InwardResidentModel.fromJson({'payment_status_id': "1"});
// inwardResidentModelList[inwardResidentModelList.indexWhere((element) => item.inward_user_id == item.inward_user_id)] = InwardResidentModel(payment_status_id: "1");
});
},
minWidth: 50,
height: 25,
padding: EdgeInsets.all(8),
child: Text("Pay ₹${item.payable_amount}",
style: TextStyle(
color: Colors.deepPurple, fontSize: 13)),
)
],
)
],
),
],
);
用户模型类的样子
class InwardUserModel {
final String inward_user_id;
final String user_id;
final String payment_status_id;
final String first_name;
final String middle_name;
final String last_name;
final String amount;
InwardUserModel({
this.inward_user_id,
this.user_id,
this.payment_status_id,
this.first_name,
this.middle_name,
this.last_name,
this.amount,
});
factory InwardUserModel.fromJson(Map<String, dynamic> parsedJson) {
return InwardUserModel(
user_id: parsedJson['user_id'] ?? "",
payment_status_id: parsedJson['payment_status_id'] ?? "",
first_name: parsedJson['first_name'] ?? "",
middle_name: parsedJson['middle_name'] ?? "",
last_name: parsedJson['last_name'] ?? "",
amount: parsedJson["amount"] ?? "",
);
}
}
如何在不重新加载完整 ListView 的情况下通过单击单独更新每个项目以显示新标题并正确更改颜色?任何帮助表示赞赏。
【问题讨论】:
标签: flutter listview dart flutter-layout updates