How to store a complex json response from api in local database in flutter?

Viewed 1868

I want to save the whole json response from api. I tried SQFLITE library to store but i cant able to achieve to store a complete json as it need to store in a table format. I'm very new to flutter. can any body suggest how can i achieve this. Below i'm attaching my sample json for your reference.

{
  "result": {
    "allitems": {
      "answered_status": 0,
      "list_items": [
        {
          "is_answered": false,
          "options": [
            {
              "image_url": "assets/images/orders/jersey.jpg",
              "description": "Jersey",
              "title": "Jersey",
              "price": 23
            },
            {
              "image_url": "assets/images/orders/bat.png",
              "description": "Bat",
              "title": "Bat",
              "price": 5
            },
          ]
        }
      ],
      "no_of_items": 12,
      "title": "ALL"
    }

  },
  "status_code": 200
}
2 Answers

I was wrong about SharedPreferences in my comment. Turns out SharedPreferences doesn't support Map<dynamic, dynamic> and only up to List<String> yet.

So you can use a database management package sembast made by the same guy who made SQFLite.

You can get help with this link to convert JSON objects to Map and vice-versa.

EDIT -


You can do something like -

import 'package:sembast/sembast.dart';

Map<dynamic, dynamic> sampleMap;

// Skipping this part
sampleMap = // Retrive and convert JSON to Map

// A sample DB in the current directory
String dbPath = 'sample.db';
DatabaseFactory dbFactory = databaseFactoryIo;

// We use the database factory to open the database
Database db = await dbFactory.openDatabase(dbPath);

var store = intMapStoreFactory.store();

// Storing Map to DB
var key = await store.add(db, sampleMap);

// Retrieving values back
var record = await store.record(key).getSnapshot(db);

// From your provided sample JSON in question
var value = record["result"]["allitems"]["list_items"][0]["options"]["image_url"];

print(value);
// value = 'assets/images/orders/jersey.jpg'

Similarly, you can explore the documentation of the package for more data operations.

Convert it to a string, you can store it in shared preference.

import 'dart:convert';
...
var s = json.encode(myMap);
// or var s = jsonEncode(myMap);

json.decode()/jsonDecode() makes a map from a string when you load it.
Related