flutterdartflutter-getxflutter-sharedpreference

How to share persistent storage between isolates in flutter?


I am using android_alarm_manager_plus to run a dart isolate. In that isolate, I modify some data and I want those changes to reflect in the main isolate. Likewise, I want changes made in the main isolate to reflect in the alarm isloate.

What I have tried

Currenlty I am using get_storage to save and read data. But it isn't synchronizing between isolates.

Alarm isolate

await GetStorage.init();

// Some time later
GetStorage().write("data", data);

Main Isolate

await GetStorage.init();

// This read always occurs after the write in the alarm isolate, but it still doesn't reflect the changes made in that write.
GetStorage().read("data");

Before this, I was using shared_preferences to do the same. shared_preferences actually had a reload method which was supposed to synchronize from disk, but I am not sure how to use it in my use case.

I have also tried the ugly method of writing and reading data to a file manually. This works, but is probably slow and I have to make sure that writes don't overlap (I would prefer not to use synchronous writes since it will block the UI).


Solution

  • Use Drift for persistent storage in Flutter. It uniquely offers built-in threading support, enabling easy database operations across isolates with no extra effort.

    You might also want to explore the sqlite_async package, which you can find at https://pub.dev/packages/sqlite_async. This package is specifically designed to run SQLite operations on a separate isolate, ensuring that your UI remains responsive during database transactions.

    By utilizing these tools, you can perform database operations asynchronously, thereby keeping your application's interface smooth and responsive even during extensive database interactions.