Ayeye Brazo
Ayeye Brazo

Reputation: 3476

How to use dart class properties on private variables

My question is very simple, I hope, I have a class and then I wish to create a private property that is the sum of 2 others... how can I achieve it?

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

  final int a;
  final int b;

  int _c = a + b; // errors
}

Errors:

The instance member 'a' can't be accessed in an initializer.

The instance member 'b' can't be accessed in an initializer.

Upvotes: 0

Views: 220

Answers (1)

Alex Radzishevsky
Alex Radzishevsky

Reputation: 3768

I believe the proper way for you to initialize _c is:

class Test {
  Test({this.a, this.b}) : _c = a + b;

  final int a;
  final int b;
  final int _c;
}

Upvotes: 2

Related Questions