How to store map in sharedpreferences flutter

To store a map in SharedPreferences in Flutter, you can follow these steps:

  1. Add the shared_preferences package to your pubspec.yaml file:

dependencies:
  shared_preferences: ^2.0.6
  
  1. Import the shared_preferences package:

import 'package:shared_preferences/shared_preferences.dart';
  
  1. Create an instance of SharedPreferences:

SharedPreferences prefs = await SharedPreferences.getInstance();
  
  1. Define your map:

Map myMap = {
  "name": "John Doe",
  "age": 25,
  "email": "johndoe@example.com",
};
  
  1. Store the map in SharedPreferences:

prefs.setString("myMap", json.encode(myMap));
  

In the above code, we encode the map as a JSON string using the json.encode() function and then store it using the setString() method of SharedPreferences.

  1. To retrieve the map from SharedPreferences:

String jsonString = prefs.getString("myMap");
Map retrievedMap = json.decode(jsonString);
  

Here, we retrieve the JSON string using the getString() method and then decode it back to a map using the json.decode() function.

Remember to import the dart:convert package for using the json.encode() and json.decode() functions.

This is a basic example of how to store a map in SharedPreferences in Flutter. You can modify it based on your specific requirements or use cases.

Leave a comment