shared_prefernce without await

Updated 29 April 2023


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:-

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:-

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

Step-2 Setup shared_pregerence

Now, we are going to set up a class to manage all the inputs and outputs with shared_prefernce

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.

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

While reading the values

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.

. . .

Leave a Comment

Your email address will not be published. Required fields are marked*

Be the first to comment.

Start a Project

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home