简体   繁体   中英

How to make an ListView.builder or List index static in Dart Flutter

I am building a flutter app that increment a index value on a list as a result of a user's interaction.

class _CheckoutScreenState extends State<CheckoutScreen>{
List<int> quantity = [1, 2, 1, 6];
void increment(int index){
 setState((){
   quantity[index] +=1;
 });
}
void decrement(int index){
  if(quantity[index] != 0){
  setState((){
   quantity[index] -=1;
 });
}
}
@override
Widget build(BuildContext context){
 return ListView.builder(
 itemBuilder: (BuildContext context, index) {
  return quantity[index] != 0 ? 
   ListTile(
    leading: IconButton(
    icon: Icon(Icons.remove),
    onPressed: (){
     decrement(index);
    }
   ),
   trailing: IconButton(
    icon: Icon(Icons.add),
    onPressed: (){
     increment(index);
    }
   ),
   title: Text('${quantity[index].toString()} products')
  )
 }
 )
}
}

When I run this code, and then remove an item (once an item is 0, it is not displayed on the screen), the index is shifted as ListView.Builder rebuilds. For example, if I removed the item (making its quantity 0) at index 2, the index should look like

  [1,2,0,6]

but as a result of the list view builder, the index shifts, and the listview builder only has

  [1,2,6]

which is discontinous from the main list. How do I make this index static in listView builder so it won't be shifted whenever it needs to be rebuilt

用 Map 替换 List 并将当前索引数量显示为 Map,这样每个 map key 代表一个唯一标识符

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM