Home > OS >  Is there any way for a constructor to require certain values egg. non-negative ints
Is there any way for a constructor to require certain values egg. non-negative ints

Time:09-04

I want to ensure I don't ever accidentally pass a negative value to my class is there any way to require the cycleCount variable to be positive the way I require it to be an int or do I just have to implement checks within the code using it?

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();
}

CodePudding user response:

you can use assert after setting your constructor with the condition that should be true to make it work without any exception, and the message if the condition is 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();
}
  • Related