thumbnail

Constant Constructor In Dart

Published on 29 March 2020
Last Updated on 29 March 2020

Use of Constant Constructor In Dart

Constant constructors are similar to parameterized constructors however if your class is comprised of fields and data points that never change then these fields can be converted into a compile time constants.

How to define and use constant constructors is demonstrated in examples given below.

Where constant constructors can not be used

If all fields encapsulated inside the class are not final fields then that class can not make use of constant constructor.

For example:

// program to demonstrate const constructor can not be used in a class with non final fields

class Person {
  final String firstName;

  // non final field
  String lastName;

  // parameterized constructor
  const Person(this.firstName, this.lastName);
}

Class given above has non final field lastName in it. Because all fields in the class are not final fields above class can’t make use of constant constructor.

Program Using Constant Constructor

Program using default con

// program to demonstrate use of const constructor

class Color {
  final int red;
  final int green;
  final int blue;

  // default constant constructor
  const Color(this.red, this.green, this.blue);
}

main(List<String> args) {
  var colorA = const Color(1, 2, 3);

  // const keyword is optional
  var colorB = Color(1, 2, 3);

  print('''
colorA.red : ${colorA.red}
colorA.green: ${colorA.green}
colorA.blue: ${colorA.blue}
''');

  print('''
colorB.red : ${colorB.red}
colorB.green: ${colorB.green}
colorB.blue: ${colorB.blue}
  ''');
}

Above program produces following output:

colorA.red : 1
colorA.green: 2
colorA.blue: 3

colorB.red : 1
colorB.green: 2
colorB.blue: 3

Caveat

Objects created by constant constructors are not always compile time constants.

We hope that you have found this guide useful for learning constant constructors in Dart.