首页 > 解决方案 > Flutter 将列表映射到对象

问题描述

您好,我有一个包含食谱的数据库。那些有标题,成分等等。但现在我需要将数据转换为我的应用程序的对象。但是问题来了,我不知道如何用颤振映射对象中的事物列表。包含成分的表有三列,一个是唯一的成分 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'],
    );


//...

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

标签: sqlsqliteflutterdart

解决方案


我不知道您从 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"
      }
    ]
  }
]

现在,我将在 quicktype 上粘贴示例 json 。

它使用 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);
}

推荐阅读