So I need to count the number of objects in the List that have a field with the value "Category.walking". I tried iterating over with both "for" loop and "forEach".
int countPets(){
int count = 0;
pets.forEach((element) {
if (pets.contains(category.walking)){
count ;
}
}
);
return count;
}
But there is only one mistake - "Undefined name 'category'. Try correcting the name to one that is defined, or defining the name." or The name 'Category' is defined in the libraries 'package:flutter/src/foundation/annotations.dart (via package:flutter/foundation.dart)' and 'package:petts/data.dart'. Try using 'as prefix' for one of the import directives, or hiding the name from all but one of the imports.
This is how i made the data set in data.dart----
enum Category { walking, grooming, doctor, shop }
enum Condition { park, cafe, training }
class Pet {
String name;
String location;
String distance;
String condition;
Category category;
String imageUrl;
bool favorite;
bool newest;
Pet(this.name, this.location, this.distance, this.condition, this.category,
this.imageUrl, this.favorite, this.newest);
}
List<Pet> getPetList() {
return <Pet>[
Pet(
"",
"",
"",
"",
Category.walking,
"",
true,
true,
),
Pet(
"",
"",
"",
"",
Category.walking,
"",
false,
false,
),
Pet(
"",
"",
"",
"",
Category.grooming,
"",
true,
true,
),
];
}
And this in how i use this getPetList() in home_page.dart----
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
List<Pet> pets = getPetList();
...there i need a counter...
Please, help me
CodePudding user response:
Try this:
for (var element in pets) {
if (element.category == Category.walking){
count ;
}
}
CodePudding user response:
Try this code.... Pass your list as a parameter to this method and it will return the desired count.
int countPets(List<Pet> pets) {
int count = 0;
pets.forEach((element) {
if (element.category == Category.walking) {
count ;
}
});
return count;
}
CodePudding user response:
try using where then length
final count = getPetList().where((e)=>
e.category.name == Category.walking.name ).length;
print(count);
//result 2