Reputation: 1954
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.. ?
Upvotes: 12
Views: 41468
Reputation: 179
Suppose you have a list like
List list =[{id=11,name=aaaa},{id=12,name=bbbb},{id=13,name=ccc}];
We have to find index of that object from list.
var data ={id=12,name=bbbb};
int index = list.indexof(data);
Now, you can update list
list[index] = {id=12,name=fffffff}
Upvotes: 1
Reputation: 387
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.."
)
);
Upvotes: 8
Reputation: 9
Suppose you have a list like
List list =[{id=11,name=aaaa},{id=12,name=bbbb},{id=13,name=ccc}];
And now you have just index data which will be update Suppose
var data ={id=12,name=bbbb};
int index = list.indexof(data);
Now Update list as
list.insert(index,{id=12,name=fffffff});
Now output is
print(list);
// [{id=11,name=aaaa},{id=12,name=fffffff},{id=13,name=ccc}];
Upvotes: 0
Reputation: 9274
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');
Upvotes: 18
Reputation: 30123
Widgets should be immutable (with final fields) and not meant to be manipulated by a parent widget.
Usually you are not supposed to store a list of widgets. Widgets should be rebuilt from scratch whenever the build
method is called.
Instead, store the displayed data in a separate data structure (e.g. create a class ReplyTileData
) with mutable fields. This data structure should be stored in your State
class.
In the build
method, read the data and instantiate your ReplyTile
widgets with the current data.
When you want to modify the data, surround the modifying code with setState
. This will trigger a complete rebuild (build
called again).
Upvotes: 2