How to upsert items in Flutter
157
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);
}
Author by
Jack Spicy
Updated on January 01, 2023Comments
-
Jack Spicy over 1 year
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 }
-
OMi Shah over 2 yearschange
_
totext
and then within callbacklist.add(text)
. I meanonChanged: (text) { list.add(text); }
-
Jack Spicy over 2 years@OMi Shah it adds a lot of items because onChanged function is working, thanks
-
Jack Spicy over 2 yearsI want to add so only one item will stay in list
-
OMi Shah over 2 yearsIt will keep adding every change, that's what it does!!
-
OMi Shah over 2 yearsthen
list.insert(1, text);
should work. -
OMi Shah over 2 yearsIt will keep replacing the element at index 1 and will insert if it's empty.
-
Jack Spicy over 2 yearsthanks let me try that
-
-
Jack Spicy over 2 yearsThanks, but the Insert method is not working for this situation because it inserts, and adds a new list of items even if index exist. Like in the database I need to have something like UPSERT. Upsert updates an item on a specific index
-
OMi Shah over 2 yearsthis should work as your
Wanted result: ['Hello', 'NewHello']
. If you want to just update the old value with new value just pass the correct index to the old element. -
Jack Spicy over 2 yearsIt gives me
['Hello', 'Hell', 'Hel', 'He', 'H']
-
OMi Shah over 2 years@JackSpicy, my mistake. I have updated my answer. This will fulfill your need.
-
Jack Spicy over 2 yearslist is growable. So when length is increasing, it adds a new item (by your example)
: list.add(text)
When onChanged function triggers it gives'Hello', 'Hell', ...
again. I need function that will add an item with index, and later only update it -
OMi Shah over 2 yearsThat's what I gave you in my updated answer. Maybe you might have then made some mistake. Kindly edit your post and add your complete code with my solution.