我試圖從用戶為我的應用程式輸入的出生日期計算寵物的年齡(以年、月和日為單位)。但是,當我嘗試輸出結果時,它給了我“'PetsAge' 實體”而不是實際計算的輸出。
這是我的代碼:
class PetsAge {
int years;
int months;
int days;
PetsAge({ this.years = 0, this.months = 0, this.days = 0 });
}
class PetDetailView extends StatelessWidget {
final Pet pet;
PetDetailView({Key key, @required this.pet}) : super(key: key);
PetsAge getPetsAge(String birthday) {
if (birthday != '') {
var birthDate = DateTime.tryParse(birthday);
if (birthDate != null) {
final now = new DateTime.now();
int years = now.year - birthDate.year;
int months = now.month - birthDate.month;
int days = now.day - birthDate.day;
if (months < 0 || (months == 0 && days < 0)) {
years--;
months = (days < 0 ? 11 : 12);
}
if (days < 0) {
final monthAgo = new DateTime(now.year, now.month - 1, birthDate.day);
days = now
.difference(monthAgo)
.inDays 1;
}
return PetsAge(years: years, months: months, days: days);
} else {
print('getTheKidsAge: not a valid date');
}
} else {
print('getTheKidsAge: date is empty');
}
return PetsAge();
}
}
我在卡片中這樣稱呼它:
Widget petsAgeCard() {
return Card(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
ListTile(
leading: Image(
image: AssetImage("Assets/images/age.png"),
),
title: Text(
"Your Pet's Age",
style: TextStyle(
fontSize: 30, fontWeight: FontWeight.w500
),
),
subtitle: Text("${getPetsAge(pet.dob.year.toString())}"),
),
],
),
);
}
uj5u.com熱心網友回復:
這是預期的行為,因為您回傳一個PetsAge物件。你可以直接String從你的getPetsAge方法而不是物件中回傳 a 。
或者,您可以覆寫toString物件的方法并僅回傳年齡,但我認為這樣做不是一個好主意。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/382528.html
下一篇:在熊貓中滾動平均值后重新采樣
