首页 > 解决方案 > 如何使用重复项编辑列表项

问题描述

我有一个动态列表,其ListView.builder() & ListTile()方法可能包含重复项,我想编辑一个项目,但我的问题是它检查列表中该值的第一次出现。
要进行编辑,我的列表图块中有 longpress 属性,它会打开一个警报对话框进行编辑
例如(也请参阅图像):[a,b,c,d,a] 我想在索引 4 处编辑 'a' 让我们说' e',但我的程序编辑了它的第一次出现。

final _items = List();
final TextEditingController addeditem = TextEditingController(text: '');  // for adding items
final TextEditingController editeditem = TextEditingController(text: '');  // for editing items
// I have an alert dialog where there is an input field and button to edit the
TextField(
    decoration: InputDecoration(
        hintText: 'Edit Item',
    ),
    controller: editeditem,
),
TextButton(
    child: Text('Done'),
    onPressed: (){
        _editItem();   // this calls the edit item logic
        Navigator.of(context).pop();
    }
)// alert dialog ends here 
// edit item logic 
void _editItem(){
    setState(() {
      int target = 0;
      for(int i=0; i<index; i++){ // I am new to dart and don't know the function right now 
        if(_items[i] == value){   // so hard coded a for loop for checking selected item
          target = i;             // and replace it
          break;
        }
      }
      _items[target] = editeditem.text; // text editing controller to replace item with new value
});

编辑后
编辑后

问候,

标签: androidflutterlistviewdart

解决方案


我建议您创建一个将用作对象的类,然后覆盖 equals 方法以验证唯一项目的身份(您也可以使用https://pub.dev/packages/equatable)。

例子:

    class Item extends Equatable {

          final int id; // unique key to differance the object
          String text;
          // It will check with this id for the unique value
          @override
          List<Object> get props => [this.id];
    }

现在,您将这个项目类用于您的列表,该列表仅包含一个字符串。

void _editItem(){
  setState(() {
    this._items[this._items.indexOf(value)].text = editeditem.text;
  }

或者你也可以将点击的 ListTile 的索引传递给编辑函数,然后你可以像这样修改:

void _editItem(int index){
  setState(() {
    this._items[index] = editeditem.text;
  }

希望对你有帮助


推荐阅读