所以我需要計算串列中具有值為“Category.walking”的欄位的物件數量。我嘗試使用“for”回圈和“forEach”進行迭代。
int countPets(){
int count = 0;
pets.forEach((element) {
if (pets.contains(category.walking)){
count ;
}
}
);
return count;
}
但只有一個錯誤 - “未定義名稱'類別'。嘗試將名稱更正為已定義的名稱,或定義名稱。” 或名稱“類別”在庫“package:flutter/src/foundation/annotations.dart (via package:flutter/foundation.dart)”和“package:petts/data.dart”中定義。嘗試對其中一個匯入指令使用“作為前綴”,或者對除一個匯入之外的所有指令隱藏名稱。
這就是我在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,
),
];
}
這就是我在 home_page.dart 中使用這個 getPetList() 的方式----
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...
請幫我
uj5u.com熱心網友回復:
嘗試這個:
for (var element in pets) {
if (element.category == Category.walking){
count ;
}
}
uj5u.com熱心網友回復:
試試這個代碼.... 將您的串列作為引數傳遞給此方法,它將回傳所需的計數。
int countPets(List<Pet> pets) {
int count = 0;
pets.forEach((element) {
if (element.category == Category.walking) {
count ;
}
});
return count;
}
uj5u.com熱心網友回復:
嘗試使用 where 然后長度
final count = getPetList().where((e)=>
e.category.name == Category.walking.name ).length;
print(count);
//result 2
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/442669.html
上一篇:顫振|將價值從孩子傳遞給父母
下一篇:為加載影像創建欄位
