In this blog, we are going to learn how to use “shared_preference without await”.
First, What is Shared Preference? and why do we use it
There may come a time when you want to persist data in your Flutter app so you can reuse it later. A common use case for this functionality is storing login credentials to be recalled the next time the user launches the app.
With Shared Preference, you can configure your Flutter app to remember the data even after the user terminates their activity. This can be used to store critical data such as passwords, tokens, and complex relational data.
Read more about our Flutter app development company.
Second, What is await ?
The function you want to run asynchronously would have some expensive operation in it like file I/O (an API call to a RESTful service)or some sort of more common computation.
For example:-
1 2 3 4 |
void main() async { await hello(); print('all done'); } |
As a result, “all done’ will print after completing the job of the “hello” function.
Third, what is the relation between shared_preference and await?
As you can check in the documentation of “shared_preference” you have to use the “await” function to initialize the object of shared_preference then you also have to use await while storing data.
For example:-
1 2 3 |
final prefs = await SharedPreferences.getInstance(); await prefs.setInt('counter', 10); |
Now, let’s start the implementation of shared_preference without await keyword.
Step-1 Adding required packages
For using the shared_preference you have to add the package in your “pubspec.yaml” file
Also, add the package for GetX which will help us to implement shared_preference without await
1 2 3 |
dependencies: shared_preferences: ^2.0.15 get: ^4.6.5 |
Step-2 Setup shared_pregerence
Now, we are going to set up a class to manage all the inputs and outputs with shared_prefernce
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
import 'package:get/get.dart'; import 'package:shared_preferences/shared_preferences.dart'; class AppSharedPref { //===============Keys for session=============// static const CART_COUNT = "cart_count"; //===========Initialize and inject============/// static Future<bool> initSessionManager() async { var _prefs = await SharedPreferences.getInstance(); Get.put(_prefs); return true; } //-----------Cart Count--------------// static setCartCount(String count) { SharedPreferences _pref = Get.find(); _pref.setString(CART_COUNT, count); } static String getCartCount() { SharedPreferences _pref = Get.find(); return _pref.getString(CART_COUNT) ?? "0"; } //--------------------------------------// } |
Step-3 Initialize the shared_preference
Now, In this step, we are going to initialize our shared_preference and then with the help of GetX we will inject the instance.
1 2 3 4 5 |
void main() async { WidgetsFlutterBinding.ensureInitialized(); await AppSharedPref.initSessionManager(); runApp(const MyApp()); } |
In the main function, before starting our application we have initialized and injected our shared_preference.
As a result, now we don’t have to use await function again and again while reading and writing data with shared_preference.
Step-4 Let’s use the above code
While writing the value
1 2 3 4 5 6 7 8 |
ElevatedButton( onPressed: () { AppSharedPref.setCartCount("1"); }, child: Text( 'Add', style: Theme.of(context).textTheme.headline6, ),) |
While reading the values
1 2 3 4 5 6 7 8 |
ElevatedButton( onPressed: () { print(AppSharedPref.getCartCount()); }, child: Text( 'Add', style: Theme.of(context).textTheme.headline6, ),) |
As you can see in the above example we have not used any await keyword while reading and writing values in the shared preference.
Here, we have learned the use of shared_preference without await keyword.
Hopefully, this blog will be helpful to you. If you have any queries, please write them in the comment sectioon.