nylo-core / nylo

Nylo is the fastest way to build your next Flutter mobile app. Streamline your projects with Nylo's opinionated approach to building Flutter apps. Develop your next idea ⚡️

Home Page:https://nylo.dev

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Edit item in collection ?

RoxDevvv opened this issue · comments

edit item in collection ?
await NyStorage.addToCollection("a_storage_key", newItem: "1");

maybe something builtin like that will be good

static Future updateInCollection<T>(int index, T newItem,
    {required String key}) async {
  List<T> collection = await readCollection<T>(key);
  if (collection.isEmpty || index < 0 || index >= collection.length) return;

  collection[index] = newItem;
  await saveCollection<T>(key, collection);
}

Hi @RoxDevvv,

This is a cool idea!

I'll work on it later today and hopefully push it up for tomorrow 🚀

Hi @RoxDevvv,

updateCollectionByIndex now available in nylo_framework v5.20.9 🔥

Here's an example of how to use it.

await NyStorage.updateCollectionByIndex(2, (item) {
      return 'New value';
}, key: 'my_storage_key');


// Example on a Model
await NyStorage.updateCollectionByIndex<User>(5, (User item) {
  item.name = "User Updated";
  item.email = "updated@aol.com";
  return item;
}, key: 'my_storage_key');

You can run this example to demo it working too:

await NyStorage.delete('coins');

await NyStorage.addToCollection('coins', item: 0);
await NyStorage.addToCollection('coins', item: 1);
await NyStorage.addToCollection('coins', item: 2); // update this
await NyStorage.addToCollection('coins', item: 3);

List<dynamic> coins = await NyStorage.readCollection('coins');
print('before');
for (var coin in coins) {
      print(coin);
}

// update
await NyStorage.updateCollectionByIndex(2, (item) {
      return 200;
}, key: 'coins');

print('\n');

print('after');
coins = await NyStorage.readCollection('coins');
// before
for (var coin in coins) {
      print(coin);
}