0

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.

Ayeye Brazo
  • 3,316
  • 7
  • 34
  • 67
  • Does this answer your question? [Dart assigning to variable right away or in constructor?](https://stackoverflow.com/questions/64546212/dart-assigning-to-variable-right-away-or-in-constructor) – jamesdlin Mar 24 '21 at 18:56

1 Answers1

2

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;
}
Alex Radzishevsky
  • 3,416
  • 2
  • 14
  • 25