Flutter-无法从api响应中将所有json数据保存到Iterable列表中编辑:(无法从Iterable列表中获取数据)

时间:2020-01-02 09:57:46

标签: json api flutter dart

我有一个返回一些数据的api。我只需要从api提取菜肴数据。问题是当我从api响应中获取数据时,第一道菜数据仅保存到iteratable list

编辑

我无法从可迭代列表中获取数据

api如下所示

  [
  {

    "restaurant_name": "Cafe",
    "restaurant_image": "http://restaurants.unicomerp.net/images/Restaurant/1010000001.jpg",
    "table_id": "1",
    "table_name": "Table 01",
    "branch_name": "Cafe",
    "nexturl": "http://snapittapp.snapitt.net/api/menu/10/?org=1010000001&branch_id=1000000001&limit=10&offset=20&lang=en",
    "table_menu_list": [
      {
        "menu_category": "Salads and Soup",
        "menu_category_id": "11",
        "menu_category_image": "http://restaurants.unicomerp.net/images/Restaurant/Item/ItemGroup_11.jpg",
        "nexturl": "http://snapittapp.snapitt.net/api/menu/20/?org=1010000001&branch_id=1000000001&menuCat=11&limit=10&offset=20&lang=en",
        "category_dishes": [
          {
            "dish_id": "100000001",
            "dish_name": "Spinach Salad",
            "dish_price": 7.95,
            "dish_image": "http://restaurants.unicomerp.net//images/Restaurant/1010000001/Item/Items/100000001.jpg",
            "dish_currency": "SAR",
            "dish_calories": 15,
            "dish_description": "Fresh spinach, mushrooms, and hard-boiled egg served with warm bacon vinaigrette",
            "dish_Availability": true,
            "dish_Type": 2,
            "nexturl": "http://snapittapp.snapitt.net/api/menu/30/?org=1010000001&branch_id=1000000001&menuItem=100000001&limit=10&offset=20&lang=en",
            "addonCat": [
              {
                "addon_category": "Spicy/Non-Spicy",
                "addon_category_id": "104",
                "addon_selection": 0,
                "nexturl": "http://snapittapp.snapitt.net/api/menu/40/?org=1010000001&branch_id=1000000001&menuItem=100000001&menuAddonCat=104&menuAddonselc=0&limit=10&offset=20&lang=en",
                "addons": [
                  {
                    "dish_id": "100000032",
                    "dish_name": "Non Spicy",
                    "dish_price": 25,
                    "dish_image": "http://restaurants.unicomerp.net/images/Restaurant/Item/Item_100000025.jpg",
                    "dish_currency": "SAR",
                    "dish_calories": 15,
                    "dish_description": "Non Spicy",
                    "dish_Availability": true,
                    "dish_Type": 1
                  }
                ]
              },
              {
                "addon_category": "Add On",
                "addon_category_id": "101",
                "addon_selection": 1,
                "nexturl": "http://snapittapp.snapitt.net/api/menu/40/?org=1010000001&branch_id=1000000001&menuItem=100000001&menuAddonCat=101&menuAddonselc=1&limit=10&offset=20&lang=en",
                "addons": [
                  {
                    "dish_id": "100000020",
                    "dish_name": "fried onions",
                    "dish_price": 15,
                    "dish_image": "http://restaurants.unicomerp.net/images/Restaurant/Item/Item_100000020.jpg",
                    "dish_currency": "SAR",
                    "dish_calories": 10,
                    "dish_description": "fried onions",
                    "dish_Availability": true,
                    "dish_Type": 2
                  }
                ]
              }
            ]
          },
          {
            "dish_id": "100000003",
            "dish_name": "Traditional New England Seafood Chowder",
            "dish_price": 12,
            "dish_image": "http://restaurants.unicomerp.net/images/Restaurant/1010000001/Item/Items/100000003.jpg",
            "dish_currency": "SAR",
            "dish_calories": 30,
            "dish_description": "with clams, scallops, and shrimp,",
            "dish_Availability": true,
            "dish_Type": 1,
            "nexturl": "http://snapittapp.snapitt.net/api/menu/30/?org=1010000001&branch_id=1000000001&menuItem=100000003&limit=10&offset=20&lang=en",
            "addonCat": []
          },
          {
            "dish_id": "100000004",
            "dish_name": "Salad Bar Soup",
            "dish_price": 5,
            "dish_image": "http://restaurants.unicomerp.net/images/Restaurant/1010000001/Item/Items/100000004.jpg",
            "dish_currency": "SAR",
            "dish_calories": 30,
            "dish_description": "Flour Mixed with fresh green leafy vegetables",
            "dish_Availability": true,
            "dish_Type": 2,
            "nexturl": "http://snapittapp.snapitt.net/api/menu/30/?org=1010000001&branch_id=1000000001&menuItem=100000004&limit=10&offset=20&lang=en",
            "addonCat": []
          },
          {
            "dish_id": "100000005",
            "dish_name": "chicken-soup",
            "dish_price": 14.89,
            "dish_image": "http://restaurants.unicomerp.net/images/Restaurant/1010000001/Item/Items/100000005.jpg",

            "dish_id": "100000029",
            "dish_name": "Tacos",
            "dish_price": 25,
            "dish_image": "http://restaurants.unicomerp.net/images/Restaurant/Item/Item_100000029.jpg",
            "dish_currency": "SAR",
            "dish_calories": 225,
            "dish_description": "Mexican Street Tacos",
            "dish_Availability": true,
            "dish_Type": 3,
            "nexturl": "http://snapittapp.snapitt.net/api/menu/30/?org=1010000001&branch_id=1000000001&menuItem=100000029&limit=10&offset=20&lang=en",
            "addonCat": []
          }
        ]
      }
    ]
  }
]

api中有一个名为 addonCat 的数据类别,我需要将其忽略,然后从响应中获取数据时继续进行下一个尝试。

api_model.dart ,这是我从api响应中获取数据的地方

class CategoryDishes {
  final String dishId;
  final String dishName;
  final double dishPrice;
  final String dishImage;
  final String dishCurrency;
  final double dishCalories;
  final String dishDescription;
  final bool dishAvailability;
  final double dishType;
  final String nexturl;

  //final List<AddonCat> _addonCat;

  CategoryDishes(
      {this.dishId,
      this.dishName,
      this.dishPrice,
      this.dishImage,
      this.dishCurrency,
      this.dishCalories,
      this.dishDescription,
      this.dishAvailability,
      this.dishType,
      this.nexturl});

  factory CategoryDishes.fromJson(Map<String, dynamic> json) {
    return CategoryDishes(
        dishId: json['dish_id'],
        dishName: json['dish_name'],
        dishPrice: json['dish_price'].toDouble(),
        dishImage:
            json['dish_image'] ?? Constants.FOOD_PLACEHOLDER_IMAGE_ASSET_URL,
        dishCurrency: json['dish_currency'],
        dishCalories: json['dish_calories'].toDouble(),
        dishDescription: json['dish_description'],
        dishAvailability: json['dish_Availability'],
        dishType: json['dish_Type'].toDouble(),
        nexturl: json['nexturl']);
  }

  static Resource<List<CategoryDishes>> get all {
    return Resource(
        url: Constants.FOOD_API_URL,
        parse: (response) {
          final result = json.decode(response.body.toString());
          //  print(response);
          Iterable list = result[0]['table_menu_list'][0]['category_dishes'];
          debugPrint("=========== Dish_List ==============\n" + list.toString());
          debugPrint("====================================");
          return list.map((model) => CategoryDishes.fromJson(model)).toList();
        });
  }
}

web.service.dart

class Resource<T> {
  final String url;
  T Function(Response response) parse;

  Resource({this.url, this.parse});
}

class Webservice {
  Future<T> load<T>(Resource<T> resource) async {
    final response = await http.get(resource.url);
    if (response.statusCode == 200) {
     // debugPrint("------D------>\n" + response.body);
      return resource.parse(response);
    } else {
      throw Exception('Failed to load data!');
    }
  }
}

main.dart

https://pastebin.com/NuDKYCCD

现在,我可以将数据保存到Iterable List中,但是不能从列表中将数据提取到card元素中。在main.dart上方是我正在获取数据的地方。

如何实现?

编辑

我只能在api中获得dishlist的第一部分,在第一类之后,有很多可用的菜式,我需要获取所有菜式并将其显示在相应的标签,请参阅上面的api链接以了解api的用法。

任何建议都会有所帮助。

3 个答案:

答案 0 :(得分:4)

它实际上保存数据。但是使用debugPrint时,它不会在控制台上打印。

您必须在wrapWidth中输入debugPrint,这样才能看到完整的响应存储在变量中。

debugPrint(
  "=========== Dish_List ==============\n" + list.toString(),
  wrapWidth: 1000,
);
debugPrint("====================================");

我认为这是您面临的问题。

您还可以进行精美印刷,使其易于理解

debugPrint(
  "=========== Dish_List ==============",
);
JsonEncoder encoder = new JsonEncoder.withIndent('  ');
debugPrint('${encoder.convert(list)}', wrapWidth: 1000);
debugPrint("====================================");

答案 1 :(得分:2)

列出所有菜肴

Container(
            color: Colors.white,
            padding: EdgeInsets.fromLTRB(5, 10, 5, 10),
            child: ListView.builder(
            itemCount:  apiResponse[0]['table_menu_list'][0]['category_dishes'].length,
              itemBuilder:(cc,ind){
                return ListTile(
                title:Text(apiResponse[0]['table_menu_list'][0]['category_dishes'][ind]['dish_name'])
                  //use other properties as your requirement
                );
              }
            ))

从网络获取日期。我使用了本地数据分配!替换为您自己的方法

void assignData(){
    apiResponse = [
  {

    "restaurant_name": "Cafe",
    "restaurant_image": "http://restaurants.unicomerp.net/images/Restaurant/1010000001.jpg",
    "table_id": "1",
    "table_name": "Table 01",
    "branch_name": "Cafe",
    "nexturl": "http://snapittapp.snapitt.net/api/menu/10/?org=1010000001&branch_id=1000000001&limit=10&offset=20&lang=en",
    "table_menu_list": [
      {
        "menu_category": "Salads and Soup",
        "menu_category_id": "11",
        "menu_category_image": "http://restaurants.unicomerp.net/images/Restaurant/Item/ItemGroup_11.jpg",
        "nexturl": "http://snapittapp.snapitt.net/api/menu/20/?org=1010000001&branch_id=1000000001&menuCat=11&limit=10&offset=20&lang=en",
        "category_dishes": [
          {
            "dish_id": "100000001",
            "dish_name": "Spinach Salad",
            "dish_price": 7.95,
            "dish_image": "http://restaurants.unicomerp.net//images/Restaurant/1010000001/Item/Items/100000001.jpg",
            "dish_currency": "SAR",
            "dish_calories": 15,
            "dish_description": "Fresh spinach, mushrooms, and hard-boiled egg served with warm bacon vinaigrette",
            "dish_Availability": true,
            "dish_Type": 2,
            "nexturl": "http://snapittapp.snapitt.net/api/menu/30/?org=1010000001&branch_id=1000000001&menuItem=100000001&limit=10&offset=20&lang=en",
            "addonCat": [
              {
                "addon_category": "Spicy/Non-Spicy",
                "addon_category_id": "104",
                "addon_selection": 0,
                "nexturl": "http://snapittapp.snapitt.net/api/menu/40/?org=1010000001&branch_id=1000000001&menuItem=100000001&menuAddonCat=104&menuAddonselc=0&limit=10&offset=20&lang=en",
                "addons": [
                  {
                    "dish_id": "100000032",
                    "dish_name": "Non Spicy",
                    "dish_price": 25,
                    "dish_image": "http://restaurants.unicomerp.net/images/Restaurant/Item/Item_100000025.jpg",
                    "dish_currency": "SAR",
                    "dish_calories": 15,
                    "dish_description": "Non Spicy",
                    "dish_Availability": true,
                    "dish_Type": 1
                  }
                ]
              },
              {
                "addon_category": "Add On",
                "addon_category_id": "101",
                "addon_selection": 1,
                "nexturl": "http://snapittapp.snapitt.net/api/menu/40/?org=1010000001&branch_id=1000000001&menuItem=100000001&menuAddonCat=101&menuAddonselc=1&limit=10&offset=20&lang=en",
                "addons": [
                  {
                    "dish_id": "100000020",
                    "dish_name": "fried onions",
                    "dish_price": 15,
                    "dish_image": "http://restaurants.unicomerp.net/images/Restaurant/Item/Item_100000020.jpg",
                    "dish_currency": "SAR",
                    "dish_calories": 10,
                    "dish_description": "fried onions",
                    "dish_Availability": true,
                    "dish_Type": 2
                  }
                ]
              }
            ]
          },
          {
            "dish_id": "100000003",
            "dish_name": "Traditional New England Seafood Chowder",
            "dish_price": 12,
            "dish_image": "http://restaurants.unicomerp.net/images/Restaurant/1010000001/Item/Items/100000003.jpg",
            "dish_currency": "SAR",
            "dish_calories": 30,
            "dish_description": "with clams, scallops, and shrimp,",
            "dish_Availability": true,
            "dish_Type": 1,
            "nexturl": "http://snapittapp.snapitt.net/api/menu/30/?org=1010000001&branch_id=1000000001&menuItem=100000003&limit=10&offset=20&lang=en",
            "addonCat": []
          },
          {
            "dish_id": "100000004",
            "dish_name": "Salad Bar Soup",
            "dish_price": 5,
            "dish_image": "http://restaurants.unicomerp.net/images/Restaurant/1010000001/Item/Items/100000004.jpg",
            "dish_currency": "SAR",
            "dish_calories": 30,
            "dish_description": "Flour Mixed with fresh green leafy vegetables",
            "dish_Availability": true,
            "dish_Type": 2,
            "nexturl": "http://snapittapp.snapitt.net/api/menu/30/?org=1010000001&branch_id=1000000001&menuItem=100000004&limit=10&offset=20&lang=en",
            "addonCat": []
          },
          {
            "dish_id": "100000005",
            "dish_name": "chicken-soup",
            "dish_price": 14.89,
            "dish_image": "http://restaurants.unicomerp.net/images/Restaurant/1010000001/Item/Items/100000005.jpg",

            "dish_id": "100000029",
            "dish_name": "Tacos",
            "dish_price": 25,
            "dish_image": "http://restaurants.unicomerp.net/images/Restaurant/Item/Item_100000029.jpg",
            "dish_currency": "SAR",
            "dish_calories": 225,
            "dish_description": "Mexican Street Tacos",
            "dish_Availability": true,
            "dish_Type": 3,
            "nexturl": "http://snapittapp.snapitt.net/api/menu/30/?org=1010000001&branch_id=1000000001&menuItem=100000029&limit=10&offset=20&lang=en",
            "addonCat": []
          }
        ]
      }
    ]
  }
];
  }
}

屏幕截图 Screenshot

答案 2 :(得分:1)

问题出在这里,您只对结果中的第一项和table_menu_list进行操作


  static Resource<List<CategoryDishes>> get all {
    return Resource(
        url: Constants.FOOD_API_URL,
        parse: (response) {
          final result = json.decode(response.body.toString());
          //  print(response);
          Iterable list = result[0]['table_menu_list'][0]['category_dishes'];
          debugPrint("=========== Dish_List ==============\n" + list.toString());
          debugPrint("====================================");
          return list.map((model) => CategoryDishes.fromJson(model)).toList();
        });
  }

解析函数,我会这样

final result = json.decode(response.body.toString());
          //  print(response);
List<CategoryDishes> list = []
List.from(result).forEach((item) =>
List.from(item['table_menu_list']).forEach((menuItem) => 
  List.from(menuItem['category_dishes']).forEach((dish) => 
   list.add(CategoryDishes.fromJson(dish))
)
)
);
debugPrint("=========== Dish_List ==============\n" + list.toString());
debugPrint("====================================");
return list;

如果您不想在列表中重复食用(具有相同ID的菜肴),则可以使用地图

final result = json.decode(response.body.toString());
          //  print(response);
Map<String, CategoryDishes> map = {}
List.from(result).forEach((item) =>
List.from(item['table_menu_list']).forEach((menuItem) => 
  List.from(menuItem['category_dishes']).forEach((dish) => 
   map[dish['dish_id']] = CategoryDishes.fromJson(dish);
)
)
);
return map.values.toList();