在使用 SQLite 存储对象之前,您需要序列化对象列表。
首先,您不能将Map或List直接存储在数据库中,您需要先将Map或List转换为JSONString,查看https://dart.dev/guides/json了解如何使用@987654329 @ 在 Dart 中
import 'dart:convert';
final data = {
"images": [
{
"id": 10,
"name": "img1"
},
{
"id": 11,
"name": "img2"
}
],
};
final String dataAsJson = json.encode(data);
其次,使用Flutter sqflite package创建一个SQLite数据库,并创建一个包含以下列的表:
id 自动递增
data 将从 API 获取的数据存储为 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
);
最后,使用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]);
如果您只想存储来自 API 的 images,则无需转换为 JSON,创建包含列 id 和 name 的表并插入。
await db.insert('images', {'id': 10, 'name': 'img1'});
await db.insert('images', {'id': 11, 'name': 'img2'});