如何在Flutter中将对象数据列表存储在SQLite中?使用API获取的是Json数据。
{
"images": [
{
"id": 10,
"name": "img1"
},
{
"id": 11,
"name": "img2"
}
]
}
在使用SQLite存储对象列表之前,您需要对其进行序列化。
首先,您不能直接将Map
或List
存储到数据库中,您需要先将Map
或List
转换为JSON String
,请查看https://dart.dev/guides/json以了解如何在Dart中使用JSON
import 'dart:convert';
final data = {
"images": [
{
"id": 10,
"name": "img1"
},
{
"id": 11,
"name": "img2"
}
],
};
final String dataAsJson = json.encode(data);
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]);
图像(images)
,则无需将其转换为JSON格式,只需创建一个带有id
和name
列的表并插入即可。await db.insert('images', {'id': 10, 'name': 'img1'});
await db.insert('images', {'id': 11, 'name': 'img2'});
class_time_table
中不存在名为“data”的列,请添加所述的列后重试。 - HasanAlyazididb.execute('ALTER TABLE ..')
添加缺失的列 data
。请参阅 https://www.sqlitetutorial.net/sqlite-alter-table。 - HasanAlyazidi