【发布时间】:2022-01-18 12:36:03
【问题描述】:
我试图从用户为我的应用程序输入的出生日期计算宠物的年龄,以年、月和日为单位。但是,当我尝试输出结果时,它给了我“'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())}"),
),
],
),
);
}
【问题讨论】: