在 sqflite 中保存单个模型是很容易的。我正在尝试将嵌套模型保存在 sqfilte 中。模型类、建表查询、错误解释如下。任何帮助保存此类嵌套模型的帮助将不胜感激:
主要型号:
@JsonSerializable(explicitToJson: true)
class Album {
String? name;
int? playcount;
String? url;
ArtistDetail? artist;
List<Image>? image;
Album({this.name, this.playcount, this.url, this.artist, this.image});
factory Album.fromJson(Map<String, dynamic> json) =>
_$AlbumFromJson(json);
Map<String, dynamic> toJson() => _$AlbumToJson(this);
}
子模型:
@JsonSerializable()
class Image {
dynamic _text;
String? _size;
dynamic get text => _text;
String? get size => _size;
Image({dynamic text, String? size}) {
_text = text;
_size = size;
}
factory Image.fromJson(Map<String, dynamic> json) => _$ImageFromJson(json);
Map<String, dynamic> toJson() => _$ImageToJson(this);
}
将图像存储到 sqflite 的函数:
// Table creation query
//'CREATE TABLE $TABLE ( $ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, $ALBUM_NAME //TEXT, $PLAY_COUNT INTEGER, $ALBUM_URL TEXT, $ARTIST_DETAIL TEXT, $IMAGES TEXT )'
//Function to perform insertion:
Future<int> insert(Album album) async {
var dbClient = await db;
return await dbClient.insert(
TABLE,
album.toJson(),
conflictAlgorithm: ConflictAlgorithm.replace,
);
}
错误:
Invalid argument [{#text: https:5d72a77281bec2f7ddea87c48.png, size: small}] with type List<Map<String, dynamic>>. The only num, String, and Uint8List are supported.
最佳答案
事实上,SQLite 不支持嵌套列表或映射,仅在“根”级别支持简单类型(String、num 和 Uint8List)。您必须以某种方式“展平”您的模型。
对于内部对象,您可以决定将艺术家详细信息保存为 JSON 文本,或者将每个艺术家字段放入专辑对象中。 对于列表,您也可以将列表编码为 JSON 或使用专有格式。
您可以找到here嵌套对象解决方案的示例。
例如,不支持以下简单 map :
{
"title": "Table",
"size": {"width": 80, "height": 80}
}
它应该被压平。一种解决方案是修改 map 结构:
CREATE TABLE Product (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT,
width INTEGER,
height INTEGER)
{"title": "Table", "width": 80, "height": 80}
另一个解决方案是将嵌套映射和列表编码为 json(或其他格式),声明列 作为字符串。
CREATE TABLE Product (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT,
size TEXT
)
{
'title': 'Table',
'size': '{"width":80,"height":80}'
};
关于database - flutter 中使用 sqflite 保存嵌套模型的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68471462/