Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SharedPreferences commit method showing deprecated inside flutter

Tags:

flutter

dart

I am using below code to save the values at sharedPreferences

_onChanged(bool value) async {
  sharedPreferences = await SharedPreferences.getInstance();
  setState(() {
    checkValue = value;
    sharedPreferences.setBool("check", checkValue);
    sharedPreferences.setString("username", username.text);
    sharedPreferences.setString("password", password.text);
    sharedPreferences.commit();
    getCredential();
  });
}

But while using I found that commit method is deprecated, So what will be the replacement for it?

like image 985
Jitesh Mohite Avatar asked Aug 26 '19 03:08

Jitesh Mohite


People also ask

What is the difference between commit () and apply () method in SharedPreferences ()?

We can call commit() or apply() to save the values in the SharedPreferences file. The commit() saves the values immediately whereas apply() saves the values asynchronously.

What is the difference between apply () and commit () on the editor?

commit() writes its data to persistent storage immediately, whereas apply() will handle it in the background.

Why is SharedPreferences Editor apply () better than SharedPreferences editor commit () for saving preferences from the main thread?

Unlike commit() , which writes its preferences out to persistent storage synchronously, apply() commits its changes to the in-memory SharedPreferences immediately but starts an asynchronous commit to disk and you won't be notified of any failures.


1 Answers

You don't need to use commit() anymore since every set (setString, setBool, etc.) executes a commit already.

On iOS, synchronize is deprecated (this is what commit() does on iOS to persist the values), so commit() wasn't needed anymore.

On Android, executing a commit on every set has always been the default behaviour, so commit() is redundant on Android.

In summary, just invoking the set methods should be fine for both Android and iOS.

Source: SharedPreferences' API documentation

like image 89
Terence Ponce Avatar answered Sep 18 '22 20:09

Terence Ponce