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);
}
Share:
157
Jack Spicy
Author by

Jack Spicy

Updated on January 01, 2023

Comments

  • Jack Spicy
    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
      OMi Shah over 2 years
      change _ to text and then within callback list.add(text). I mean onChanged: (text) { list.add(text); }
    • Jack Spicy
      Jack Spicy over 2 years
      @OMi Shah it adds a lot of items because onChanged function is working, thanks
    • Jack Spicy
      Jack Spicy over 2 years
      I want to add so only one item will stay in list
    • OMi Shah
      OMi Shah over 2 years
      It will keep adding every change, that's what it does!!
    • OMi Shah
      OMi Shah over 2 years
      then list.insert(1, text); should work.
    • OMi Shah
      OMi Shah over 2 years
      It will keep replacing the element at index 1 and will insert if it's empty.
    • Jack Spicy
      Jack Spicy over 2 years
      thanks let me try that
  • Jack Spicy
    Jack Spicy over 2 years
    Thanks, 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
    OMi Shah over 2 years
    this 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
    Jack Spicy over 2 years
    It gives me ['Hello', 'Hell', 'Hel', 'He', 'H']
  • OMi Shah
    OMi Shah over 2 years
    @JackSpicy, my mistake. I have updated my answer. This will fulfill your need.
  • Jack Spicy
    Jack Spicy over 2 years
    list 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
    OMi Shah over 2 years
    That'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.