Jack Spicy
Jack Spicy

Reputation: 93

How to upsert items in Flutter

I have a list

List<String> list = ['Hello']

I have TextField which has onChanged callback.

Question: How I can UPSERT an item to List when TextField triggers onChanged function

Wanted result: ['Hello', 'NewHello']


onChanged: (_) {
 // What I should do with list. Thanks
}

Upvotes: 1

Views: 288

Answers (1)

OMi Shah
OMi Shah

Reputation: 6186

You need to check if the list length is 2, if it is then update the value at index 1; if the length is less then simply add the change to the list.

Use the add method on the list to insert the change.

Change _ to text and then within the callback:

onChanged: (text) {
     list.length == 2 ? list[1] = text : list.add(text);
}

Upvotes: 1

Related Questions