How to Save a List of Objects in Shared Preferences in Flutter?

Shared Preferences allow us to save and retrieve data in the form of key-value pairs. This data is persistent meaning that it remains stored even when the user closes the app. Saving data in this manner is often used for small amounts of data that need to be accessed frequently such as user preferences, settings, and cached data. 

In this blog post, we’re going to be discussing how to save a list of objects into Shared Preferences using setStringList() method in Flutter.

This method can store a list of strings (List<String>) to shared_preferences.

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

class ExamplePage extends StatefulWidget {
  const ExamplePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  State<ExamplePage> createState() => _ExamplePageState();
}

class _ExamplePageState extends State<ExamplePage> {

  final List<Car> _cars = [
    Car(id: 1, name: "Huyndai"),
    Car(id: 2, name: "Toyota"),
    Car(id: 3, name: "KIA"),
    Car(id: 4, name: "Peugeot"),
    Car(id: 5, name: "Tesla"),
  ];

  @override
  void initState() {

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(widget.title)),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            ..._cars.map((car) => Text(car.name!)),
            Row(
              children: [
                OutlinedButton(onPressed: () async{
                  final prefs = await SharedPreferences.getInstance();
                  List<String> saveData = [];
                  for(Car car in _cars){
                    saveData.add(jsonEncode(car.toJson()));
                  }
                  prefs.setStringList('cars_pref', saveData);
                }, child: const Text("Save")),
                OutlinedButton(onPressed: () async{
                  final prefs = await SharedPreferences.getInstance();
                  List<String> loadData = prefs.getStringList('cars_pref') ?? [];
                  for(var data in loadData){
                    var car = Car.fromJson(jsonDecode(data));
                    print(car);
                  }
                }, child: const Text("Load")),
              ],
            )
          ],
        ),
      ),
    );
  }
}

class Car {
  final int? id;
  final String? name;

  Car({this.id, this.name}) : super();

  factory Car.fromJson(Map<String, dynamic> json){
    return Car(
      id: json['id'],
      name: json['name']
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'name': name,
    };
  }

}

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close