what is the right/efficient way to update List if I add a new item for DB in Flutter

50 views Asked by At

Currently if there is a list in db, and I wanna add a new item, I have to use following method:

  List<String> contentsList = [];

  updateList() async{
    contentsList.clear();

    ProfilesProvider profilesProvider = ProfilesProvider();
    contentsList = await profilesProvider.updateProfileSpeech(profile: profile);
    
  }

So clear the whole contentsList, which means refresh totally, I guess it is not so efficient, since I just update one Item but have to update whole list, What I thought is not to catch data from db, instead just adding this item to List meanwhile save it into db

  updateList2(String newItem) async{
    contentsList.add(newItem);
  }

But in this way if I edit / delete / add an item I have to create different method and need to know the right index, is there a better solution or thoughts?

I am just learning coding, is it the right way to handle such issue? thanks!

1

There are 1 answers

0
Rahul On

Provide key to every list item while modifying the list. Each key passed should be unique among all the items in list.

Flutter uses keys to identify items if they get changed.

Don't do this: return ListTile(key: ValueKey(index))

Do this: return ListTile(key: valueKey(data[index].id)

This way, even if an item is added to the middle of the list, flutter will know which widget subtree belonged to which data. The entire list won't be refreshed but only portion needed to be rebuilt will be. Flutter does this under the hood.