【问题标题】:How to edit a list item in flutter with duplicate items如何使用重复项编辑列表项
【发布时间】:2021-03-04 01:01:44
【问题描述】:

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

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

编辑后

问候,

【问题讨论】:

    标签: android flutter listview dart


    【解决方案1】:

    我建议您创建一个将用作对象的类,然后覆盖 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;
      }
    

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-18
      • 1970-01-01
      • 2020-03-18
      • 1970-01-01
      • 1970-01-01
      • 2023-03-07
      • 1970-01-01
      • 2013-03-28
      相关资源
      最近更新 更多