gpt4 book ai didi

sql - Flutter将列表映射到对象

转载 作者:行者123 更新时间:2023-12-03 04:43:44 25 4
gpt4 key购买 nike

您好,我有一个包含食谱的数据库。那些有标题,成分等等。但是现在我需要将数据转换为我的应用程序的对象。但是,这里出现了一个问题,我不知道如何用抖动来映射对象中的事物列表。包含成分的表有三列,成分ID是唯一的,配方ID是指配方(因此不唯一)和成分名称。我有添加它的方法,但是我收到错误信息“Uint8ArrayView”不是“列表”类型的子类型,以解决此问题。我使用了.toString(),但这不适用于成分。因为它的类型为List而不是od类型的字符串。

What I already got:

//...
return Recipe(
id: i,
name: parsedTitle[i]['Rezept_Title'].toString(),
ingredients: //Here is where I need help,
preperation: parsedPreperation[i]['Zubereitung'].toString(),
imageUrl: imgUrl[i]['Image_URL'],
);


//...
我希望你能帮助我。谢谢!

最佳答案

我不知道您从api获得的json,但可以说它是

[
{
"id": 1,
"name": "Recipe name1",
"ingredients": [
{
"name": "ingredient 1",
"quantity": "1 tbsp"
},
{
"name": "ingredient 2",
"quantity": "1 tbsp"
}
]
},
{
"id": 2,
"name": "Recipe name2",
"ingredients": [
{
"name": "ingredient 1",
"quantity": "1 tbsp"
}
]
}
]
现在,我将粘贴示例json here on quicktype
它使用json为我生成所有必需的类。只需跳过下面的代码(该代码是从站点生成的),即可查看实际的代码。

// To parse this JSON data, do
//
// final recipe = recipeFromJson(jsonString);

import 'dart:convert';

List<Recipe> recipeFromJson(String str) => List<Recipe>.from(json.decode(str).map((x) => Recipe.fromJson(x)));

String recipeToJson(List<Recipe> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class Recipe {
Recipe({
this.id,
this.name,
this.ingredients,
});

int id;
String name;
List<Ingredient> ingredients;

factory Recipe.fromJson(Map<String, dynamic> json) => Recipe(
id: json["id"] == null ? null : json["id"],
name: json["name"] == null ? null : json["name"],
ingredients: json["ingredients"] == null ? null : List<Ingredient>.from(json["ingredients"].map((x) => Ingredient.fromJson(x))),
);

Map<String, dynamic> toJson() => {
"id": id == null ? null : id,
"name": name == null ? null : name,
"ingredients": ingredients == null ? null : List<dynamic>.from(ingredients.map((x) => x.toJson())),
};
}

class Ingredient {
Ingredient({
this.name,
this.quantity,
});

String name;
String quantity;

factory Ingredient.fromJson(Map<String, dynamic> json) => Ingredient(
name: json["name"] == null ? null : json["name"],
quantity: json["quantity"] == null ? null : json["quantity"],
);

Map<String, dynamic> toJson() => {
"name": name == null ? null : name,
"quantity": quantity == null ? null : quantity,
};
}


使用:
假设您正在使用 http包来获取json。
var response = await http.get('your_url_for_json');
var body = response.body;

final recipes = recipeFromJson(body);//the first commented line from the generated code.
现在,您只需使用 .即可获取所有值 recipes.first.id作为第一个条目的ID。 recipes.first.ingredients.first.name为第一个条目的成分名称。
循环也可以
for(var r in recepis){
print(r.id);
}

关于sql - Flutter将列表映射到对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62654769/

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