Flutter: Best Way to store data locally (You will be needing for almost every App)
Flutter is being used largely by mobile App developers nowadays in which you will be seeing a lot of third party packages for some utilities. Sometimes it becomes hard to find the best or suitable package to use for some certain task.
Here I am gonna discuss about local storage and a lot packages are available also on pub.dev. Its sometime hard to differentiate between these and find the efficient and easy to use one.
As a Android developer you may have used shared preferences multiple times. Even if you haven’t used it, being new to mobile app development, the first local storage utility which you will hear for storing data locally is Shared Preferences. I also have heard about it and used it multiple times but I noticed that the operations in Shared Preferences are async and we have to make our own methods async and wait for it to retrieve data from shared preferences.
Later I have seen hive databases which are also key value pair kind of Databases. I also found it difficult using it as a beginner in flutter.
Later I have seen getStorage Package offered by Getx community and I really found it awesome.
It almost supports every platform supported by flutter. Its quite easy to use and perform operation in Milliseconds without waiting for it. We can use it anywhere within our Applications code without being conscious about efficiency and performance.
First of all you have to add this package to your pubspec.yaml file as like other packages.
dependencies:
get_storage:
Now import in your Dart
code :
import ‘package:get_storage/get_storage.dart’;
Then you have to initialize it in your main method of App.
main() async {
await GetStorage.init();
runApp(App());
}
Now make an instance of GetStorage() class and use it anywhere inside your dart code.
final box = GetStorage();
To write information you must use write:
box.write(yourkey, 'Your Value');
Here value can be of any type. You can also write your custom Classes objects by serializing it into json.
box.write('user', jsonEncode(user));
Then to read your values from storage:
print(box.read('quote'));
You can also remove your specific value from storage using:
box.remove('quote');
And at the end you can remove your storage from device whenever you no longer need it. e,g. user tokens etc.
box.erase();
I found this package very useful and helpful in storage single or smaller type of values and its super efficient.
Github.