如何在 Flutter 上的 sqlite 中存储对象数据列表?

9 dart flutter

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

{
     "images": [
        {
          "id": 10,
          "name": "img1"
        },
        {
          "id": 11,
          "name": "img2"
        }
      ]
}
Run Code Online (Sandbox Code Playgroud)

Has*_*idi 6

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

Map首先, or不能List直接存储在数据库中,需要先将Mapor转换List为 JSON String,查看https://dart.dev/guides/json了解如何JSON在 Dart 中使用

import 'dart:convert';

final data = {
     "images": [
        {
          "id": 10,
          "name": "img1"
        },
        {
          "id": 11,
          "name": "img2"
        }
      ],
};

final String dataAsJson = json.encode(data);
Run Code Online (Sandbox Code Playgroud)

其次,使用Flutter sqflite 包创建一个 SQLite 数据库并创建一个包含以下列的表: id自动增量 data将从 API 获取的数据存储为 JSONdataAsJson

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
);


Run Code Online (Sandbox Code Playgroud)

最后,使用以下命令从数据库中获取数据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]);
Run Code Online (Sandbox Code Playgroud)

如果您只想存储images来自 API 的数据,则无需转换为 JSON、创建包含列idname插入的表。

await db.insert('images', {'id': 10, 'name': 'img1'});
await db.insert('images', {'id': 11, 'name': 'img2'});
Run Code Online (Sandbox Code Playgroud)