I have tried to calculate the age of a pet in years, months and days, from the date of birth which the user inputs for my application. However, when I am trying to output the results, it is giving me "Instance of 'PetsAge'" instead of the actual calculated output.
Here is my code:
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();
}
}
This is how I called it in a Card:
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())}"),
),
],
),
);
}
CodePudding user response:
This is the expected behavior because you return a PetsAge
object. You can directly return a String
from your getPetsAge
method instead of the object.
OR, you can override the toString
method of your object and return the age only but i think it is not a good idea to do like this.