0

Why we cannot put variable a into myList like this?

When I am doing this the compiler says The instance member 'a' can't be accessed in an initializer. Try replacing the reference to the instance member with a different expression which is not clear for me.

If this then how can I able to get the data from a in method age() ?

Can any body help me to understand what is going here??

class Test {
  int a = 5;

  List<int> all = [a];

  int age() {
    int b = a * 5;
    return b;
  }
}

But when I copy myList and paste in the constructor like this it is working fine. what is the reason behind this?

class Test {
 int a = 5;

 Test() {
   List<int> myList = [a];
 }

 int age() {
   int b = a * 5;
   return b;
 }
}

I found one post about this but it was not clear what is the reason behind this.

  • 1
    See https://stackoverflow.com/a/64548861/ and https://stackoverflow.com/a/63319094/. When you initialize inline in the class definition, it's initialized early, before `this` exists. Consequently, it cannot depend on other instance members. – jamesdlin Nov 13 '20 at 20:18
  • Yes, some how it does. thanks a lot – Aakash Shrestha Nov 14 '20 at 07:41

0 Answers0