Zohaib Hamdule
Zohaib Hamdule

Reputation: 658

For loop is behaving wierdly in Dart. I am trying to make an async function to retrive data

I am trying to make an asynchronous function to get data from an API and use it in a FutureBuilder in Flutter. But the for loop inside the function is behaving very wierdly. It is only executing the statement just below the for loop heading.

Future<List<Dish>> getData() async {

List<Dish> cuisineDishes;

Response response = await get('https://api.spoonacular.com/recipes/search?apiKey=$apiKey&cuisine=$cuisineType&number=$number');
Map data = jsonDecode(response.body);

for (int i=0; i<number; i++)
{ print('111');
  cuisineDishes[i].dishName = data['results'][i]['title'].toString();  
  String dishID = data['results'][i]['id'].toString(); 
  print('222');

  Response response2 = await get('https://api.spoonacular.com/recipes/$dishID/ingredientWidget.json?apiKey=$apiKey');
  Map ingredientsData = jsonDecode(response2.body);

  String ingredientsString;
  List<String> ingredients;

  for (int j =0; j<ingredientsData['ingredients'].toList().length; j++)
  {
    ingredientsString += '${ingredientsData['ingredients'][j]['name']} ';
  }

  ingredients = ingredientsString.split(' ');
  cuisineDishes[i].ingredients = ingredients;
  cuisineDishes[i].dishType = ' ';
  cuisineDishes[i].special = 0;

}

return cuisineDishes;

}

In this case only 111 is being printed. There is nothing wrong with the API request and I tried putting data['results'][i]['title'].toString() in print which is returning a proper string ('Curry Rice with Chickpeas'). Printing data['results'][i]['id'] also prints a valid ID.

Here is the Dish Class :-

class Dish
{
  String dishType;
  String dishName;
  List<String> ingredients;
  int special;

  Dish([this.dishType, this.dishName, this.ingredients, this.special=0]);


  Map<String, dynamic> toMap() {

    String ingredientsText = ingredients[0];
    for (int i=1; i<ingredients.length; i++)
    ingredientsText += " ${ingredients[i]}";

    return {

      'dishType': dishType,
      'dishName' : dishName,
      'ingredients' : ingredientsText,
      'special' : special

    };
  }

}

Please Help

Upvotes: 0

Views: 55

Answers (2)

Zohaib Hamdule
Zohaib Hamdule

Reputation: 658

It was a simple mistake List<Dish> cuisineDishes; should be List<Dish> cuisineDishes = new List(); because it is a growable list.

Upvotes: 0

Braj
Braj

Reputation: 626

You might need to add to the map after the response. Also the data['results'] must be giving a List>, you need to cast that one as well before reaching inside its nest.

Upvotes: 1

Related Questions