lesnitsky / flutter_localstorage

📦 LocalStorage for Flutter
MIT License
301 stars 60 forks source link

Give more control to users over the package performance #100

Closed ThomasGysemans closed 11 months ago

ThomasGysemans commented 11 months ago

My updates allow the developer to better control when the data is written down on the JSON file.

If for example the user is storing a huge amount of data (several megabytes for example), data fetched from a database for a future offline mode maybe, then the developer will want their users to be able to delete the data, or to control it. In the event that multiple keys must be deleted using deleteItem(String key), looping over the keys one by one and calling this method is extremely slow as the file is re-written at every single iteration. That behaviour is not ideal.

My update introduces a new way to control when the write and delete operations are made.

To delete multiple items:

BAD

List<String> keys = ["a", "b", "c"];
for (String key in keys) {
  storage.deleteItem(key);
}

GOOD

// much faster if there is a lot of data in `storage`
storage.deleteItems(["a", "b", "c"]);

To set multiple items

BAD

storage.setItem("a", someBigAmountOfData());
storage.setItem("b", severalMegabytesMaybe());
storage.setItem("c", thatsHuge());
// ...

GOOD

storage.setItem("a", someBigAmountOfData(), write: false);
storage.setItem("b", severalMegabytesMaybe(), write: false);
storage.setItem("c", thatsHuge(), write: false);
// ...
storage.writeData(); // saves the data locally now

New helper features

It is also possible to get the exact amount of bytes stored in the JSON file:

int bytes = await storage.getStorageSize();
print("The file is ${(bytes / 1024).toStringAsFixed(3)} KiB");

NOTE: calling getStorageSize() on the web will always raise a PlatformNotSupportedError.

Breaking changes

The only breaking change concerns the parameters of setItem(). Indeed, toEncodable is no longer an optional positional argument. Here the exact signature:

// lib/localstorage.dart
Future<void> setItem(
  String key,
  value, {
  Object Function(Object nonEncodable)? toEncodable,
  bool write = true
});
lesnitsky commented 11 months ago

It's not mentioned anywhere in docs or readme, but this package is intended to be exactly the same as the web LocalStorage. It doesn't have any methods like writeData or optional write arg.

I understand the problem this PR is trying to solve, although the proposed way is not acceptable, since it will break compatibility with the web implementation of LocalStorage.