Flutter将列表映射到对象

时间:2020-06-30 09:54:22

标签: sql sqlite flutter dart

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

我已经得到的:

//...
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'],
    );


//...

希望您能帮助我。谢谢!

1 个答案:

答案 0 :(得分:1)

我不知道您从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);
}