如何在Flutter中将对象数据列表存储到SQLite?

14

如何在Flutter中将对象数据列表存储在SQLite中?使用API获取的是Json数据。

{
     "images": [
        {
          "id": 10,
          "name": "img1"
        },
        {
          "id": 11,
          "name": "img2"
        }
      ]
}

https://www.tutorialspoint.com/sqlite/sqlite_insert_query.htm,https://dev59.com/d3RB5IYBdhLWcg3wbGxB - Robert Harvey
1个回答

6

在使用SQLite存储对象列表之前,您需要对其进行序列化。

首先,您不能直接将MapList存储到数据库中,您需要先将MapList转换为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);

其次, 使用Flutter sqflite包创建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格式,只需创建一个带有idname列的表并插入即可。
await db.insert('images', {'id': 10, 'name': 'img1'});
await db.insert('images', {'id': 11, 'name': 'img2'});

在传递 JSON 值时,如果出现以下错误,则表示未处理的异常:DatabaseException(table class_time_table has no column named data (Sqlite code 1 SQLITE_ERROR): , while compiling: INSERT OR REPLACE INTO class_time_table (data) VALUES (?), (OS error - 2:No such file or directory)) sql 'INSERT OR REPLACE INTO class_time_table (data) VALUES (?)' args [[{"class_name":"9TH","section_name":"A","subject_n...] - Adnan haider
错误提示表class_time_table中不存在名为“data”的列,请添加所述的列后重试。 - HasanAlyazidi
我已经添加了它,但仍然面临问题,以下是代码:db.execute('CREATE TABLE time_table(id INTEGER PRIMARY KEY AUTO_INCREMENT, data TEXT,)'); - Adnan haider
更新后的代码 db.execute('CREATE TABLE class_time_table(id INTEGER PRIMARY KEY AUTO_INCREMENT, data TEXT,)') - Adnan haider
如果之前的 SQLite 数据库文件仍然存在,您需要首先删除它,然后使用新的文件名创建一个新的数据库,或者只是使用 db.execute('ALTER TABLE ..') 添加缺失的列 data。请参阅 https://www.sqlitetutorial.net/sqlite-alter-table。 - HasanAlyazidi
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接