Dart : Const Constructor

Dart : Const Constructor

·

1 min read

Const Constructor

  • Dart const constructor and how to use it to make all objects of a class constant at compile time.

  • Immutability means being unable to be changed. If a value is immutable, that value cannot be changed.

  • To make a field of a class immutable, you can use either the const or final keyword.

  • If you use the const keyword, you need to initialize the value in the field declaration. Also, the value must be known at compile time.

  •   final type fieldName;
    
class Text {
  final String content;
  Text({this.content = ''});
}

void main() {
  const text = Text(content: 'Hello');
  print(text.content);
}