将一个小部件的值(年龄)传递给另一个小部件

时间:2021-05-08 05:03:32

标签: flutter class datetime variables

通过文本框输入,使用以下代码获取用户的年龄(为简单起见被截断):

AnimalSound()

在终端中,年龄打印成功。然后我形成了一个类,希望将打印的值存储在这个类中:

onChanged: (valueYear) {
                          if (valueYear.length == 4)
                            FocusScope.of(context).unfocus();
                          valueYearKey = valueYear;
                          valueBirthKey = valueDayKey +
                              '-' +
                              valueMonthKey +
                              '-' +
                              valueYearKey;
                          print(valueBirthKey);
                          DateTime _dateTime = DateTime(
                            int.parse(valueBirthKey.substring(6)),
                            int.parse(valueBirthKey.substring(3, 5)),
                            int.parse(valueBirthKey.substring(0, 2)),
                          );
                          age = DateTime.fromMillisecondsSinceEpoch(
                                      DateTime.now()
                                          .difference(_dateTime)
                                          .inMilliseconds)
                                  .year -
                              1970;
                          print(age);
                          return age = UserAge.age;
                        })),
              ),
            ],
          ),
        ],
      ),
    );
  }
}

下面是用户按下按钮,如果年龄> 18,弹出对话框确认并继续,如果年龄< 18,未成年,另一个对话框弹出。

class UserAge with ChangeNotifier {
  static int age;
  notifyListeners();
}

页面上没有看到红色错误,但是当我点击按钮时,会弹出我的 UserAge.age 为空的错误。

这让我得出结论,从初始打印值收到的年龄没有成功存储到类中。我一直在尝试修复它,但无济于事。我是新手,如果答案正对着我,我深表歉意。非常感谢任何指导,谢谢!

1 个答案:

答案 0 :(得分:1)

使用 age = UserAge.age 代替 UserAge.age =age