user2779311
user2779311

Reputation: 1884

Can you define Const variables for any Class?

While declaring const the following observation is not understood:

const abc=[3,4,5,6]

Here we are declaring abc as const means we are fixing pointer to point to a object. Does this mean that we cannot change list members through abc i.e

abc[0]=5

or we cannot assign it a new list

abc=[5,6,7]

If a create a class abcd then i am not able to assign the object of this class to a const variable. Kindly update why so.

void main() {
  const a = [1, 2, 4, 5];
  a[0] = 7;
  print(a);
  const b = abcd();
}

class abcd {
  String name;
  String toString() {
    return name;
  }
}

Upvotes: 2

Views: 53

Answers (1)

julemand101
julemand101

Reputation: 31299

const means the value can and will be determined at compile time and can then not be changed. For lists, const means you get a list which are not modifiable. Also, the variable itself pointing to the list are marked as final and can not be modified after it has been assigned a value.

Since the object itself cannot be modified, you class needs to define a const constructor and all member of the class should not be able to be modified after assignment which therefore require fields to marked as final.

So your example should be:

void main() {
  const b = abcd('name');
  print(b);
}

class abcd {
  final String name;

  const abcd(this.name);

  @override
  String toString() {
    return name;
  }
}

I also want to add that the const constructor needs be able to figure out the value at compile time. So it is rather restricted the amount of logic you can use here.

Upvotes: 2

Related Questions