[英]Please I'm trying to update an item on a list in my flutter app without having same item with updated value
当我运行代码时,列表会添加另一个项目,而不是更新找到索引的旧项目(仍显示旧项目)。 我也尝试过在我的listView.builder()
listView.custom()
上使用键,在我创建的自定义小部件上,在listView.builder()
上渲染都给出相同的结果。 有什么我做的不对吗?
以这种方式使用indexWhere()
,
void updateProduct(String id, ProductSaver productSaver) {
final prodIndex = _productList.indexWhere((element) => element.id == id);
final newProduct = ProductSaver(
title: productSaver.title,
description: productSaver.description,
imageUrl: productSaver.imageUrl,
price: productSaver.price);
_productList[prodIndex] = newProduct as Product;
notifyListeners();
}
这样:
void updateProduct(String id, Product newItem){
final pIndex = _productList.indexWhere((element)=>element.id == id);
if(pIndex >= 0){
_productList[pIndex] = newItem;}
notifyListeners();}
我还使用了列表.contain()
void updateProduct({String? id, required Product newItem}) {
final itemIndex = _productList.indexWhere((prod) => prod.id! == id);
if (_productList.contains(_productList[itemIndex])) {
_productList[itemIndex] = newItem;
}
notifyListeners();
}
这是代码的build()
:
@override
Widget build(BuildContext context) {
final providerData = Provider.of<Products>(context);
return Scaffold(
appBar: AppBar(
title: const Text('Products'),
actions: [
IconButton(
onPressed: () {
Navigator.of(context).pushNamed(EditProductScreen.routeName);
},
icon: const Icon(
Icons.add,
size: 30,
),
)
],
backgroundColor: MyColor.primaryColor,
),
body: ListView.builder(
padding: const EdgeInsets.symmetric(horizontal: 0, vertical: 10),
itemCount: providerData.item.length,
itemBuilder: (context, index) {
return Column(
children: [
UserProductItem(
id: providerData.item[index].id!,
imageUrl: providerData.item[index].imageUrl,
title: providerData.item[index].title),
)
],
);
}),
);
}
}
上面的 UserProductItem() 小部件。
class UserProductItem extends StatelessWidget {
const UserProductItem({
Key? key,
required this.imageUrl,
required this.title,
required this.id,
}) : super(key: key);
final String imageUrl;
final String title;
final String? id;
@override
Widget build(BuildContext context) {
final productData = Provider.of<Products>(context);
return ListTile(
key: UniqueKey(),
leading: Image.network(
imageUrl,
),
title: Text(
title,
style: const TextStyle(
color: MyColor.primaryColor,
fontSize: 17,
),
),
trailing: FittedBox(
child: Row(
children: [
IconButton(
icon: const Icon(
Icons.edit,
color: Colors.green,
),
onPressed: () {
Navigator.of(context)
.pushNamed(EditProductScreen.routeName, arguments: id!);
},
),
IconButton(
icon: const Icon(
Icons.delete_outline_outlined,
color: Colors.red,
),
onPressed: () {
productData.removeItem(id!);
},
),
],
),
),
);
}
}
您更改了特定索引处的值。 相反,您可以尝试将项目添加到列表中
if (_productList.contains(_productList[itemIndex])) {
_productList.add(newItem);//<--here
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.