How to store a list of object data in SQLite on Flutter? Json data coming with API.
{
"images": [
{
"id": 10,
"name": "img1"
},
{
"id": 11,
"name": "img2"
}
]
}
How to store a list of object data in SQLite on Flutter? Json data coming with API.
{
"images": [
{
"id": 10,
"name": "img1"
},
{
"id": 11,
"name": "img2"
}
]
}
You need to serialize the list of objects before storing them using SQLite.
Firstly, you cannot store Map
or List
in the database directly, you need to convert Map
or List
to JSON String
first, check out https://dart.dev/guides/json to learn how to use JSON
in Dart
import 'dart:convert';
final data = {
"images": [
{
"id": 10,
"name": "img1"
},
{
"id": 11,
"name": "img2"
}
],
};
final String dataAsJson = json.encode(data);
Secondly, use Flutter sqflite package to create an SQLite database and create a table with the following columns:
id
auto increment
data
to store your data fetched from API as JSON dataAsJson
import 'package:sqflite/sqflite.dart';
// 1. open the database first. check the documentation of `sqflite` package
// 2. insert data to the table
await db.insert(
'images', # the name of the table
{'data': dataAsJson}, # `data` is the column's name
);
Lastly, get the data from the database using await db.query(..)
final List<Map> maps = await db.query('images', columns: ['id', 'data']);
// now let's get the first item in the table then convert it back as it was fetched from the API.
final dataFromJsonToMap = json.decode(maps[0]);
If you only want to store the images
from the API, you do not need to convert to JSON, create a table with columns id
and name
and insert.
await db.insert('images', {'id': 10, 'name': 'img1'});
await db.insert('images', {'id': 11, 'name': 'img2'});