【问题标题】:How to make an ListView.builder or List index static in Dart Flutter如何在 Dart Flutter 中将 ListView.builder 或 List 索引设为静态
【发布时间】:2021-09-25 13:29:33
【问题描述】:

我正在构建一个颤振应用程序,它会根据用户的交互来增加列表中的索引值。

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')
  )
 }
 )
}
}

当我运行此代码,然后删除一个项目(一旦项目为 0,它就不会显示在屏幕上),索引会随着 ListView.Builder 的重建而移动。 例如,如果我删除了索引 2 处的项目(使其数量为 0),则索引应如下所示

  [1,2,0,6]

但由于列表视图构建器,索引发生了变化,而列表视图构建器只有

  [1,2,6]

与主列表不连续。如何在 listView 构建器中将此索引设为静态,以便在需要重建时不会移动它

【问题讨论】:

    标签: flutter dart listview arraylist shopping-cart


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-09
      • 2020-12-18
      • 1970-01-01
      • 2021-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-19
      相关资源
      最近更新 更多