1

I'm trying to understand the following example where I try to initialize a final variable in a constructor.

1st example - works

void main() {
  
  Test example = new Test(1,2);
  
  print(example.a);  //print gives 1
    
}

class Test
{
  final int a;
  int b;

    Test(this.a, this.b);
}

2nd example doesn't work

void main() {
  
  Test example = new Test(1,2);
  
  print(example.a);  //compiler throws an error
    
}

class Test
{
  final int a;
  int b;

    Test(int a, int b){
      this.a = a;
      this.b = b;
    }
}

and when i remove final then it works again

void main() {
  
  Test example = new Test(1,2);
  
  print(example.a);  //print gives 1
    
}

class Test
{
  int a;
  int b;

    Test(int a, int b){
      this.a = a;
      this.b = b;
    }
}

what is the difference between the constructor in the 1st and the 2nd constructor why final initialization works with the first and doesn't with the 2nd.

Can anyone explain that to me please? THanks

Ayrix
  • 433
  • 5
  • 16

1 Answers1

0

You cannot instantiate final fields in the constructor body.

Instance variables can be final, in which case they must be set exactly once. Initialize final, non-late instance variables at declaration, using a constructor parameter, or using a constructor’s initializer list:

Declare a constructor by creating a function with the same name as its class (plus, optionally, an additional identifier as described in Named constructors). The most common form of constructor, the generative constructor, creates a new instance of a class

syntax in the constructor (described in https://www.dartlang.org/guides/language/language-tour#constructors):

Reham Alraee
  • 139
  • 8
  • Thanks for your answer first of all. But if you try the codes above in dartpad, you will see that it works. Or am I doing something wrong? – Ayrix Nov 05 '21 at 21:33
  • I got this: Error compiling to JavaScript: /tmp/dartpadREEHUS/lib/bootstrap.dart: Warning: Interpreting this as package URI, 'package:dartpad_sample/bootstrap.dart'. /tmp/dartpadREEHUS/lib/main.dart:15:7: Error: Field 'a' should be initialized because its type 'int' doesn't allow null. int a; ^ /tmp/dartpadREEHUS/lib/main.dart:16:7: Error: Field 'b' should be initialized because its type 'int' doesn't allow null. int b; ^ – Reham Alraee Nov 05 '21 at 21:42
  • It's not working on the dartpad – Reham Alraee Nov 05 '21 at 21:42