[SOLVED] Making non-nullable class fields not required if they have a default value

Issue

This Content is from Stack Overflow. Question asked by Andre Pena

I have the following class:

class MarkdownRenderingContextData {
  MarkdownRenderingContextData({
    required this.textSize,
    required this.textStyle
  });
  MarkdownTextSize textSize = MarkdownTextSize.text;
  MarkdownTextStyle textStyle = MarkdownTextStyle.normal;
}

What I want is:

  • If you don’t pass textStize and textStyle, they have the default value.
  • If you pass them, they must not be null.

I’m not being able to do it. Dart is forcing me to add the required in the construtor, which is making them mandatory during instanciation and I don’t want it. If I make them NOT required (e.g MarkdownTextSize?) now I have to check for null during use.

Is there any way around it?



Solution

You can specify a default value in the constructor, and make the members final:

class MarkdownRenderingContextData {
  MarkdownRenderingContextData({
    this.textSize = MarkdownTextSize.text,
    this.textStyle =  MarkdownTextStyle.normal
  });
  final MarkdownTextSize textSize;
  final MarkdownTextStyle textStyle;
}


This Question was asked in StackOverflow by Andre Pena and Answered by Peter Koltai It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?