【问题标题】:How to store list of object data in sqlite on Flutter?如何在 Flutter 上的 sqlite 中存储对象数据列表?
【发布时间】:2019-03-19 02:07:39
【问题描述】:

如何在 Flutter 上的 SQLite 中存储对象数据列表? API 附带的 Json 数据。

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

【问题讨论】:

标签: dart flutter


【解决方案1】:

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

首先,您不能将MapList直接存储在数据库中,您需要先将MapList转换为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,创建包含列 idname 的表并插入。

await db.insert('images', {'id': 10, 'name': 'img1'});
await db.insert('images', {'id': 11, 'name': 'img2'});

【讨论】:

  • 在 2 点传递 json 值然后获取它显示错误未处理异常:DatabaseException(table class_time_table has no column named data (Sqlite code 1 SQLITE_ERROR): ,同时编译:INSERT OR REPLACE INTO class_time_table (data) VALUES (?), (OS error - 2:No such file or directory)) sql 'INSERT OR REPLACE IN TO class_time_table (data) VALUES (?)' args [[{"class_name":"9TH"," section_name":"A","subject_n...]
  • 错误提示表class_time_table中没有名为data的列。添加提到的列,然后重试。
  • 我已经添加了,但这里仍然面临问题是代码 db.execute('CREATE TABLE time_table(id INTEGER PRIMARY KEY AUTO_INCREMENT, data TEXT,)');
  • 更新代码 db.execute('CREATE TABLE class_time_table(id INTEGER PRIMARY KEY AUTO_INCREMENT, data TEXT,)')
  • 如果之前的sqlite数据库文件还存在,需要先删除,用新文件名新建数据库,或者只添加缺少的列data使用db.execute('ALTER TABLE ..')见@987654323 @
【解决方案2】:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-01
    • 2020-09-30
    • 2013-05-12
    • 2013-02-07
    • 2010-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多