How to save and retrieve a List<Map> with Get Storage

Issue

I am trying to persist a simple List<Map<String,dynamic>> with GetStorage.

The documentation says:

When to use GetStorage:

  • simple Maps storage.
  • cache of http requests
  • storage of simple user information.
  • simple and persistent state
  • storage any situation you currently use sharedPreferences.

So, I did not encoded/decoded to json String.

In the end, getting error

type 'List<dynamic>' is not a subtype of type 'List<Map<String, dynamic>>?' in type cast

Here is my code, and error is thrown at box.read() method:

  final box = GetStorage();
  var payments = <Payment>[].obs;

  Future<void> savePaymentsToDB() async {
    var paymentsAsMap = payments.map((payment) => payment.toJson()).toList();
    await box.write('payments', paymentsAsMap);
  }

  void getPaymentsFromDB() {
    var result = box.read<List<Map<String, dynamic>>>('payments');
    
    if (result != null) {
      payments =
          result.map((payment) => Payment.fromJson(payment)).toList().obs;
    }
  }

Solution

You need to encode paymentsAsMap to json string. The toJson method on your model, only coverts that model to json object (key,value pair). To store that in shared preferences or getStorage you should convert that json object to string.

import 'dart:covert';

// Storing data
...
var paymentsAsMap = payments.map((payment) => payment.toJson()).toList();
String jsonString = jsonEncode(paymentsAsMap);
await box.write('payments', jsonString);

// fetching data
var result = box.read('payments');
dynamic jsonData = jsonDecode(result);
payments = jsonData.map((payment) => Payment.fromJson(payment)).toList().obs;

Answered By – HasilT

Answer Checked By – David Marino (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *