Max888
Max888

Reputation: 3770

Getter and setter extension methods

How can I add getter and setter extension methods as per below? The below doesn't work because _foo isn't defined and setting to foo directly like set foo(val) => foo = val; creates an infinite loop.

extension on Uri {
  String get foo => _foo;
  set foo(val) => _foo = val;
}

main() {
  var uri = Uri();
  uri.foo = 'bar';
}

Upvotes: 0

Views: 1473

Answers (1)

lrn
lrn

Reputation: 71693

If you want to store data on the Uri object, you need a place to store it. You can't declare extension fields because extensions don't change the class they extend, so they can't add storage to the object.

What you can do is use an Expando:

extension on Uri {
  static final _storage = Expando<String>();
  String get foo => _storage[this];
  set foo(String value) {
    _storage[this] = value;
  }
}

An Expando is intended for adding storage "on the side" for any object without leaking storage when the objects get garbage collected. (You can't use it to store values on strings, numbers, booleans or null, because those are special wrt. identity because you can create them from literals, ... and because in JavaScript they aren't real objects).

Upvotes: 1

Related Questions