How do I initialize a final class property in a co

2020-05-19 12:02发布

In Java you are allowed to do this:

class A {    
    private final int x;

    public A() {
        x = 5;
    }
}

In Dart, I tried:

class A {    
    final int x;

    A() {
        this.x = 5;
    }
}

I get two compilation errors:

The final variable 'x' must be initialized.

and

'x' can't be used as a setter because its final.

Is there a way to set final properties in the constructor in Dart?

3条回答
家丑人穷心不美
2楼-- · 2020-05-19 12:11

You can make it even shorter with this. syntax in the constructor (described in https://www.dartlang.org/guides/language/language-tour#constructors):

class Point {
  final num x;
  final num y;
  final num distanceFromOrigin;

  Point(this.x, this.y)
      : distanceFromOrigin = sqrt(pow(x, 2) + pow(y, 2));
}

If you have some more complicated initialization you should use factory constructor, and the code become:

class Point {
  final num x;
  final num y;
  final num distanceFromOrigin;

  Point._(this.x, this.y, this.distanceFromOrigin);

  factory Point(num x, num y) {
    num distance = distanceFromOrigin = sqrt(pow(x, 2) + pow(y, 2));
    return new Point._(x, y, distance);
  }
}
查看更多
3楼-- · 2020-05-19 12:15

You cannot instantiate final fields in the constructor body. There is a special syntax for that:

class Point {
  final num x;
  final num y;
  final num distanceFromOrigin;

  // Old syntax
  // Point(x, y) :
  //   x = x,
  //   y = y,
  //   distanceFromOrigin = sqrt(pow(x, 2) + pow(y, 2));

  // New syntax
  Point(this.x, this.y) :
    distanceFromOrigin = sqrt(pow(x, 2) + pow(y, 2));
}
查看更多
姐就是有狂的资本
4楼-- · 2020-05-19 12:16

I've come to a dilemma here where I wanted to initialize a final List with no items, and a Stream to be defined inside the constructor (like in this case distanceFromOrigin).

I couldn't do that with any of the answers below, but I mixed them both and it worked.

Example:

class MyBloc {
  final BehaviorSubject<List<String>> itemsStream;
  final List<String> items = [];

  MyBloc() : this.itemsStream = BehaviorSubject<List<String>>.seeded([]) {
    items.addAll(List.generate(20, (index) => "Hola! I'm number $index"));
    itemsStream.add(items);
  }
}
查看更多
登录 后发表回答