Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart make sure optional boolean in class is not null

Since it's an optional value, it will sometimes be null, so how can I avoid it throwing an error? Is this the only way to do it?

class QText extends StatelessWidget {
  QText(this.text, this.size, [this.bold]);

  final String text;
  final double size;
  bool bold;

  @override
  Widget build(BuildContext context) {
    bold = (bold == null) ? false : bold;
    return Whatever..
  }
}

I'd like to do this but of course it doesn't work:

class QText extends StatelessWidget {
  QText(this.text, this.size, [this.bold]);

  final String text;
  final double size;
  final bool bold ?? false;

  @override
  Widget build(BuildContext context) {
    return Whatever..
  }
}
like image 953
Hasen Avatar asked Dec 08 '22 11:12

Hasen


1 Answers

As the fields are final try passing the default during constructor initialization.

Also add an assert statement to make sure it's never initialized to null.

Example:

class QText extends StatelessWidget {
  QText(this.text, this.size, [this.bold = false]) : assert(bold != null);

  final String text;
  final double size;
  final bool bold;

  @override
  Widget build(BuildContext context) {}
}

Hope that helps!

like image 62
Hemanth Raj Avatar answered Feb 05 '23 16:02

Hemanth Raj