Can I define setter and getter in the attribute itself, rather than the containing class?

StackOverflow https://stackoverflow.com/questions/21464610

  •  05-10-2022
  •  | 
  •  

質問

Suppose I want my class to do things on attribute access. I can of course do that in setters and getters:

class Foo {
    set bar (v) {
        // do stuff
    }
}

However, if I want to attach the same behavior to multiple attributes, I'd have to explicitly define the same setters and getters for every one of them. (The use case I have in mind is an observable, i.e. a class that knows when its attributes are being changed).

What I'd like to do is something like:

class Foo {
    var bar = new AttributeWithAccessBehavior();
}

Python does this with descriptors - what is the closest thing in Dart?

役に立ちましたか?

解決

AFAIK there isn't anything with getter/setter syntax that you can reuse.

You could assign a function to a field, that you can access using call notation (), but you have to be careful to call the function instead of overriding the field assignment.

A similar but more powerful alternative are classes that can emulate functions (see https://www.dartlang.org/articles/emulating-functions/)

A class that has a call method can be used like a method. This is similar to assigned functions mentioned above but in addition you can store state information.

If you implement actual getter/setter you can of course delegate to whatever you want, but that is obviously not what you are looking for.

For the use case you mentioned, there is the observe package. I have no idea how exactly it solves the problem, but it works quite well.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top