【问题标题】:Getting "Instance of 'PetsAge'" instead of the actual calculated Age获取“'PetsAge'实例”而不是实际计算的年龄
【发布时间】: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())}"),
          ),
        ],
      ),
    );
  }

【问题讨论】:

    标签: android flutter datetime


    【解决方案1】:

    这是预期的行为,因为您返回 PetsAge 对象。您可以直接从您的 getPetsAge 方法返回 String 而不是对象。

    或者,您可以覆盖对象的 toString 方法并仅返回年龄,但我认为这样做不是一个好主意。

    【讨论】:

    • 感谢您的帮助!我删除了 PetsAge 课程并按照您的建议做了,它确实效果很好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-02
    • 2012-03-26
    • 2013-06-17
    • 2012-05-06
    • 2019-10-19
    • 2020-12-28
    • 2016-03-20
    相关资源
    最近更新 更多