How to assign passed value to a final field in constructor?

Issue

Code:

class MyColor {
  final Color one;
  final Color two;

  MyColor({
    this.one = Colors.black,
    this.two = one.withOpacity(0.5), // error
  });
}

Is there any way to assign the value of one to two in the constructor itself, I want all fields to be final.

Solution

class MyColor {
  final Color one;
  final Color two;

  MyColor({
    this.one = Colors.black,
    Color? two,
  }) : two = two ?? one.withOpacity(0.5);
}

Answered By – iDecode

Answer Checked By – Clifford M. (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *