5

I've an api that return some data. I only need to fetch dish data from the api. The issue is while I'm getting data from the api response, the first dish data is only saving to iteratable list.

EDIT

I can't fetch the data from Iterable List

the api is like below

  [
  {

    "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": []
          }
        ]
      }
    ]
  }
]

there is a data category called addonCat in the api, I need this to be ignored and go on to the next dish when fetching data from the response.

api_model.dart this where I'm fetching the data from response of 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

Now I can save the data to the Iterable List, but can't fetch data from the list to the card elements. Above main.dart is the place where I'm fetching the data.

How to achieve this?

EDIT

I'm only able to get the first part of the dishlist in the api, after the first category there is many of the dishes are available, I need to fetch all of the dishlist and display it to the corresponding tabs, refer above api link to know how the api is.

Any suggestions would be helpful.

3 Answers 3

4

Its actually saving the data. But its not printing on the console when using debugPrint.

You have to give wrapWidth in debugPrint, so that you can see full response stored in a variable.

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

I think this is the problem you are facing.

You can also do pretty-print to make it understandable

debugPrint(
  "=========== Dish_List ==============",
);
JsonEncoder encoder = new JsonEncoder.withIndent('  ');
debugPrint('${encoder.convert(list)}', wrapWidth: 1000);
debugPrint("====================================");
Sign up to request clarification or add additional context in comments.

10 Comments

@AllwiN Glad that helped. I also updated my answer with pretty print. you can check it.
Still when I'm trying to fetch the data to my card elements nothing shows? what am I doing wrong. this the main.dart pastebin.com/NuDKYCCD, here I'm fetching the value for the card elements.
@AllwiN I will try to find the problem. But you may want to change the question or create a new post. So that other people can also help you.
@AllwiN I am not sure what the problem is. But you may refer this code GitHub
There is an issue I'm facing, That I couldn't fetch all data from api response. Only the first array named dish only I can fetch from the response. How to get all the dishes from the api? the code remains same as I posted in the question.
|
2

Listing all the dishes

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
                );
              }
            ))

Getting date from network. I used local assignment of data ! Replace with your own method

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 Screenshot

9 Comments

Thank you bud!!.. let me try this.
cc and ind ---> context and index??
This is not working. the thing is the data is not storing to the iterable list.
Use List<Map> instead of iterable
List tmpList = apiResponse[0]['table_menu_list'][0]['category_dishes']; then get by index
|
1
+50

The problem is here that you only do it for the first item in result and in 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();
        });
  }

The parse function I would do it like this

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;

If you don't want to have repeated dishes in the list (dishes with the same id), you could use a map

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();

1 Comment

Thanku. Now I'm getting all dishes data in my screen.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.