简体   繁体   中英

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

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM