Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter Edit List Item

Tags:

flutter

dart

I have a question in my flutter dart script, this my script:

List<ReplyTile> replytile = new List<ReplyTile>();

replytile.add(
    new ReplyTile(
        member_photo: "photo",
        member_id: "001",
        date: "01-01-2018",
        member_name: "Denis",
        id: "001",
        text: "hallo.."
    )
);

My question is: how to EDIT items 'member_name' on List with id = 001.. ?

like image 366
Denis Ramdan Avatar asked Oct 14 '18 08:10

Denis Ramdan


2 Answers

This assumes a ReplyTile is a widget, if it is not, you don't need the setState calls.

If you can guarantee the item is in the list, use:

final tile = replytile.firstWhere((item) => item.id == '001');
setState(() => tile.member_name = 'New name');

If the item is not found, an exception is thrown. To guard against that, use:

final tile = replytile.firstWhere((item) => item.id == '001', orElse: () => null);
if (tile != null) setState(() => tile.member_name = 'New name');
like image 59
Jacob Phillips Avatar answered Oct 21 '22 10:10

Jacob Phillips


Below is the code to update a single item of list using the index. You can simple create an extension function for the same.

extension ListUpdate<T> on List<T> {
  List<T> update(int pos, T t) {
    List<T> list = [];
    list.add(t);
    replaceRange(pos, pos + 1, list);
    return this;
  }
}

And use it like below to replace an item.

replytile.update(
    5, new ReplyTile(
        member_photo: "photo",
        member_id: "001",
        date: "01-01-2018",
        member_name: "Denis",
        id: "001",
        text: "hallo.."
    )
);
like image 20
Shadab Hashmi Avatar answered Oct 21 '22 09:10

Shadab Hashmi