构造函数是否有任何方法需要某些值egg.非负整数



我想确保我不会意外地将负值传递给我的类。有没有办法像我要求int那样要求cycleCount变量为正,或者我只需要在使用它的代码中实现检查?

class TimerPage extends StatefulWidget {
final int cycleCount;
final int workTime;
final int breakTime;
const TimerPage(
{super.key,
required this.cycleCount,
required this.workTime,
required this.breakTime});
@override
State<TimerPage> createState() => _TimerPageState();
}

您可以在使用条件设置构造函数后使用assert,条件应为true以使其正常工作,如果条件为false则返回消息

class TimerPage extends StatefulWidget {
final int cycleCount;
final int workTime;
final int breakTime;
const TimerPage(
{Key? key,
required this.cycleCount,
required this.workTime,
required this.breakTime}) : assert(cycleCount > 0, "you can't pass a negative integer to cycleCount");
@override
State<TimerPage> createState() => _TimerPageState();
}

最新更新