How to store List in Sharedpreferences Flutter

In mobile app development, we need to store user data locally using SharedPreferences or using Database, So I am going to share with you useful tips in this article mostly we store data in SharedPreferences like int, string, bool, etc. but in this post, we will see How to store List in Sharedpreferences Flutter. Let's see step by step.

Introduction to SharedPreferences:

SharedPreferences is a built-in feature in our phones that allows us to store and retrieve small amounts of data using key-value pairs. It provides a simple and lightweight way to persistently store information such as integers, strings, lists of strings, Booleans, and doubles.

Purpose of SharedPreferences in Android and iOS:

SharedPreferences is a feature used by both Android and iOS apps to store and retrieve simple data in a designated storage area. This data remains intact even when the app is closed and reopened, allowing us to access the stored values consistently. SharedPreferences provide a persistent storage mechanism for app-specific data.

Advantages of using SharedPreferences:

There are several advantages to using SharedPreferences in Flutter let's look into them one by one.

1. Simplicity: SharedPreferences provide an easy-to-use API for storing and retrieving data. We can store data in key-value pair.

2. Lightweight: SharedPreferences is a lightweight for storing processes, we can use it for small amounts of data such as user preferences, settings, or session-related information. It does not require any external dependencies or additional setups.

3. Persistence: SharedPreferences offer persistent storage, which means we can data use even when the app is closed or the device is restarted. This allows to us for maintaining the state of the app and preserving user preferences across sessions.

4. Platform Compatibility: We can use SharedPreferences for both Android and iOS platforms. Flutter provides a consistent and unified API for accessing SharedPreferences, making it easy to develop cross-platform applications.

5. Performance: SharedPreferences operate asynchronously, ensuring that data operations do not block the main UI thread. This contributes to a smooth user experience and prevents app freezing or slowdowns during data access.

6. Security: SharedPreferences store data in an allocated space specific to the app, providing a level of isolation and security. The data is not accessible to other apps, enhancing the protection of sensitive information.

7. Flexibility: SharedPreferences support various data types, including integers, strings, booleans, doubles, and lists of strings.

8. Developer-Friendly: We can easily use various methods of SharedPreferences like editing, updating, and deleting stored values. This flexibility simplifies the management of app-specific data and reduces the development effort required for data storage operations.

 

How to store List in Sharedpreferences Flutter:

First, we need a SharedPreferences package to store data locally. So we need to add the latest package of SharedPreferences to our project's pubspec.yaml file.

dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.2
  shared_preferences: ^2.0.17

 

The second step is we need a model class for the saved that model type of object in the list. So we are going to create a model which is called ReminderModel You can see it below.

import 'dart:convert';

class ReminderModel{

  int? dayCode;
  String? dayName;
  bool? isSelected;

  ReminderModel({this.dayCode, this.dayName, this.isSelected});

  static Map toMap(ReminderModel dayModel) {
    return {
      'dayCode': dayModel.dayCode,
      'dayName': dayModel.dayName,
      'isSelected': dayModel.isSelected
    };
  }

  ReminderModel.fromMap(Map map) {
    dayCode = map['dayCode'];
    dayName = map['dayName'];
    isSelected=map['isSelected'];
  }

  static String encode(List rem) => json.encode(
    rem
        .map>((data) => ReminderModel.toMap(data))
        .toList(),
  );

  static List decode(String musics) =>
      (json.decode(musics) as List)
          .map((item) => ReminderModel.fromMap(item))
          .toList();

}

  

Then we need to create a list of ReminderModel types of objects, and that list is stored in SharedPreferences so create a list like below.

 //Create list
List reminderList = [];
     reminderList.add(ReminderModel(dayCode: 1,dayName: "Monday",isSelected: true));
     reminderList.add(ReminderModel(dayCode: 2,dayName: "Tuesday",isSelected: true));
     reminderList.add(ReminderModel(dayCode: 3,dayName: "Thursday",isSelected: true));

 //Get SharedPreferences instant to save data
 final prefs = await SharedPreferences.getInstance();

 //Store list as string
 prefs.setString("key", ReminderModel.encode(reminderList));

 

You can see we store the object of the list as a string using JSON encoding.

 static String encode(List rem) => json.encode(
    rem
        .map>((data) => ReminderModel.toMap(data))
        .toList(),
  );

 

Now we get data from SharedPreferences using JSON decoding.

static List decode(String musics) =>
      (json.decode(musics) as List)
          .map((item) => ReminderModel.fromMap(item))
          .toList();

 

Finally, you got an object list from SharedPreferences like below.

print("object"+  prefs.getString("key").toString());

 

 You can see the output on a console like below.

I/flutter (17826): List of object--->[{"dayCode":1,"dayName":"Monday","isSelected":true},{"dayCode":2,"dayName":"Tuesday","isSelected":true},{"dayCode":3,"dayName":"Thursday","isSelected":true}]

 

Full Code:

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:untitled/models/ReminderModel.dart';

class Errorgram extends StatefulWidget {
  const Errorgram({Key? key}) : super(key: key);

  @override
  State createState() => _ErrorgramState();
}

class _ErrorgramState extends State {
  @override
  void initState() {
    saveData();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
        bottom: false,
        child: Scaffold(
            appBar: AppBar(
              title: Text("Errorgram"),
            ),
            body: Center(
              child: Text(""),
            )));
  }

  saveData() async {
    final prefs = await SharedPreferences.getInstance();
    List reminderList = [];
    reminderList
        .add(ReminderModel(dayCode: 1, dayName: "Monday", isSelected: true));
    reminderList
        .add(ReminderModel(dayCode: 2, dayName: "Tuesday", isSelected: true));
    reminderList
        .add(ReminderModel(dayCode: 3, dayName: "Thursday", isSelected: true));
    prefs.setString("key", ReminderModel.encode(reminderList));

    print("List of object--->" + prefs.getString("key").toString());
  }
}

 

Conclusion:

We saw in this post How to store List in Sharedpreferences Flutter step by step in an easy way. I hope this post may help you in the future.

 

Tags: