Home > Mobile >  A value of type 'Iterable<Food>' can't be assigned to a variable of type '
A value of type 'Iterable<Food>' can't be assigned to a variable of type '

Time:12-20

Here is the Code where I am facing the error am learning from a source and the coding version is 2018 so that's why am facing the error. Basically its not an error its a confusion what to do with this. Am building a testing app for my personal use. Here is the error

import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:myapp/fake_data.dart';
import 'package:myapp/food.dart';
import 'models/category.dart';
class FoodPage extends StatelessWidget
{
   static const String routename='/FoodPage';
   Category? category;
   FoodPage({this.category});
   @override
   Widget build(BuildContext context) {
   Map<String, Category>? arguments=ModalRoute.of(context)!.settings.arguments as 
     Map<String, Category>?;
     category=arguments!['category'] ;
         Iterable<Food> foods = FAKE_FOOD.where((food) => 
    food.categoryId==this.category!.id).toList();
      return Scaffold(
              appBar: AppBar(
              title: Text('Foods From ${category!.content}'),
                 ),
                body: Center(
                     child: Center(
                             child: ListView.builder(
                                  itemCount: foods.length,
                                      itemBuilder: (context,index){
                                      Food food=foods[index];
                                      return Text(food.urlImage);
                                         }),
                                       )
                                    ),
                                   );
                                }
                              }

error is in "Food food=foods[index];" Here is food Class where I derive the food class

import 'dart:math';


class Food {
 int? id;
 String name;
 String urlImage;
 Duration duration;
 Complexity? complexity;
 List<String>? ingredients=<String>[];
 int? categoryId;
 Food({this.id,
 required this.name,
 required this.urlImage,
 required this.duration,
   this.complexity,
   this.categoryId,
   this.ingredients});
   {
    this.id=Random().nextInt(100);
   }

}
 enum Complexity
 {
  Simple,Medium,Hard
  }

CodePudding user response:

I am pretty sure this line is what is causing the error:

Iterable<Food> foods = FAKE_FOOD.where((food) => 
    food.categoryId==this.category!.id).toList();

The problem is that you cannot assign a List to a variable of the type Iterable (just like the error tells you). Since you are casting anyway I would recommend working with a List in general:

List<Food> foods = FAKE_FOOD.where((food) => 
        food.categoryId==this.category!.id).toList();

Now we are assigning a List to a variable of the type List which fixes this error.

  • Related