Home > OS >  FLUTTER- How to save a List<Object> into shared Preferences?
FLUTTER- How to save a List<Object> into shared Preferences?

Time:10-05

I want to add a product to cart and save it, so that when i open the app again, it is present in the cart. i can add multiple products to cart, so I am looking to save a List<Products>

I want to save a List into sharedPreferences and retrieve the same, but there are no methods for that. I tried using setStringList but I am unable to convert the string into object. And the data is not getting saved also.

my class model-

import 'dart:convert';

class Products {
  Products({
    required this.title,
    required this.price,
    required this.description,
    required this.image,
    this.quantity = 0,
  });

  final String title;
  final double price;
  final String description;

  final String image;
  int quantity;

  factory Products.fromRawJson(String str) =>
      Products.fromJson(json.decode(str));

  String toRawJson() => json.encode(toJson());

  factory Products.fromJson(Map<String, dynamic> json) => Products(
        title: json["title"],
        price: json["price"].toDouble(),
        description: json["description"],
        image: json["image"],
      );

  Map<String, dynamic> toJson() => {
        "title": title,
        "price": price,
        "description": description,
        "image": image,
      };
}

CodePudding user response:

The shared_preferences library has only the options to save the following.

  • int
  • string
  • List
  • double
  • boolean

Reference: https://pub.dev/documentation/shared_preferences/latest/shared_preferences/SharedPreferences-class.html

But what you could do is to create a List<String> in their jsonEncode form and save it.

Convert the List to List by encoding each of them using https://api.flutter.dev/flutter/dart-convert/jsonEncode.html

Once done you can save it and while decoding it similarly use jsonDecode

Hope this helps. Thanks!

CodePudding user response:

import 'dart:convert'; 

 //first converts your array to json string store it in session   

 String strJsonString = json.encode(arrayProducts); 
 //save strJsonString as String into your session


//when you want to retrive it from session just decode session value
List<Products> = json.decode(strJsonString);
  • Related