How to edit a list item in flutter with duplicate items

666

I would recommend you to create a class that you will use as a object and after override the equals method to verify the identity of the unique item (You can also use https://pub.dev/packages/equatable).

Example:

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

And now you use this item class for your list insted of just a String.

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

Or you could also pass to the edit function the index of the tapped ListTile pressed and then you could just modify like this:

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

Hope it helped you

Share:
666
DK_bhai
Author by

DK_bhai

Updated on December 25, 2022

Comments

  • DK_bhai
    DK_bhai over 1 year

    I have a dynamic list with ListView.builder() & ListTile() method which might contain duplicate item, I want to edit an item but my problem is it checks the first occurrence of that value in the list.
    To edit I have longpress property inside my list tile which opens a alert dialog for editing
    For example (refer image also): [a, b, c, d, a] I want to edit 'a' at index 4 to let's say 'e', but my program edits the first occurrence of 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
    });
    

    after editing
    after editing

    Regards,