gpt4 book ai didi

database - Flutter - Sembast 数据库插入对象列表

转载 作者:IT王子 更新时间:2023-10-29 07:20:09 24 4
gpt4 key购买 nike

我即将在 Flutter 中使用数据库“Sembast”。具有 string 和 int 等数据类型的简单对象可以正常工作。但是,使用列表时会出现问题。

我已经创建了一个示例并以以下教程为导向:https://resocoder.com/2019/04/06/flutter-nosql-database-sembast-tutorial-w-bloc/在我的示例中,有水果和树叶作为对象。水果包含叶子列表。

class Fruit {
final String id;
final String name;
final bool isSweet;
final List<Leaves> leaves;
...
}

class Leaves {
final String id;
final String name;
...
}

//Create a sample object
var leaveOne = Leaves(id: "1", name: "leaveOne");
var leaveTwo = Leaves(id: "2", name: "leaveTwo");
var leaveThree = Leaves(id: "3", name: "leaveThree");

var leavesList = List<Leaves>();
leavesList.add(leaveOne);
leavesList.add(leaveTwo);
leavesList.add(leaveThree);

var fruit = Fruit(id: "1", name: "Apple", isSweet: true, leaves: leavesList);
_fruitDao.insert(fruit);


// The fruitDao.insert makes following
Future insert(Fruit fruit) async {
await _fruitStore.add(await _db, fruit.toJson());
}

JSON 看起来像这样:{id: 1, name: Apple, isSweet: true, leaves: ['Leaves' 实例, 'Leaves' 实例, 'Leaves' 实例]}

错误如下:[ERROR:flutter/lib/ui/ui_dart_state.cc(148)] 未处理的异常:无效的参数:值实例'Leaves'不受支持的类型 Leaves

最佳答案

如前所述,Instance of 'Leaves' 不是有效类型,因此每个 Leave 也必须进行转换。在没有看到 toJson() 的情况下很难猜出你在做什么,但像这样的东西应该可以工作(可以在很大程度上进行优化):

class Fruit {
final String id;
final String name;
final bool isSweet;
final List<Leaves> leaves;

Fruit({this.id, this.name, this.isSweet, this.leaves});

Map<String, dynamic> toJson() => <String, dynamic>{
'id': id,
'name': name,
'isSweet': isSweet,
'leaves': leaves?.map((leave) => leave.toJson())?.toList(growable: false)
};
}

class Leaves {
final String id;
final String name;

Leaves({this.id, this.name});

Map<String, dynamic> toJson() => <String, dynamic>{'id': id, 'name': name};
}

你的 json 应该看起来像这样:

{
"id": "1",
"name": "Apple",
"isSweet": true,
"leaves": [
{
"id": "1",
"name": "leaveOne"
},
{
"id": "2",
"name": "leaveTwo"
},
{
"id": "3",
"name": "leaveThree"
}
]
}

关于database - Flutter - Sembast 数据库插入对象列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56098992/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com