Save data in shared preferences in flutter



Save data in shared preferences in flutter


'shared_preferences'- Using 'SharedPreferences' for Android and 'NSUserDefaults' for iOS.

Step 1- You need to add following dependency in your pubspec.yaml file.


  shared_preferences: ^0.4.3 (or Latest version)


Step 2- Import the following package


  import 'package:shared_preferences/shared_preferences.dart'; 


Step 3- Adding data to preferences


You can add only bool, int, String, double data to preferences.

  final prefs = await SharedPreferences.getInstance();  
  prefs.setString(key, value);



Creating Object and Adding data-


SharedPreferences shPrefs = await SharedPreferences.getInstance();  


 Adding int Value

   shPrefs.setInt('key', 1234);

 Adding String Value

   shPrefs.setString('key', "abcxyz");

 Adding bool Value

   shPrefs.setBool('key', true);

Adding double Value

   shPrefs.setDouble('key', 12.0);



Read Data from Preferences


  Read int Value

  int value =  shPrefs.getInt('key');

  Read String Value

  String value =  shPrefs.getString('key');

  Read bool Value

  bool value =  shPrefs.getBool('key');

  Read double Value

  double value =  shPrefs.getDouble('key');
 


Now the final method of adding and getting the data are-


  savePreferences('user_name', 'rohan') // Saving data
  await getPreferences('user_name');     // getting data



Saving string value in preferences


static Future savePreferences(String key, String value) async {
    final prefs = await SharedPreferences.getInstance(); 
    prefs.setString(key, value);
}


Getting string value in preferences


static Future<String> getPreferences(String key) async {
    final prefs = await SharedPreferences.getInstance(); 
    return prefs.getString(key) ?? '';
}


Clear all data from preferences when no longer needed


static Future clearPreferences() async {
   final prefs = await SharedPreferences.getInstance();  prefs.clear();
}




Previous
Next Post »