Home > OS >  Add a variable to a Dart extension method or datatype?
Add a variable to a Dart extension method or datatype?

Time:12-27

I am converting some JS code to Dart. The JS code adds some properties to an Array.

Example adding 'start' property to the Array.

var a = [1,2,3,4];
a.start = 3;

As there is a lot of this code and I'm trying to stay in line with the original JS code as much as possible, I'm trying to find a similar solution in Dart.

I've looked at extensions on types, eg the following, but not sure if they can work for variables and only work for methods ?

extension JSList<T> on List<T> { 
  int _start;
  int get start => _start;
  void set start(x) => _start = x;
}

But I seem to get various errors like

Error: Extensions can't declare instance fields

And looking at the docs, I'm not sure what I'm trying is allowed.

So is there any way to add some custom field/variables/properties to an existing List datatype ? Or are there any other similar suggestions ?

CodePudding user response:

Dart extension methods are syntactic sugar for freestanding functions to look like instance method calls. You therefore cannot directly use them to add independent data members to objects.

In some cases, you could have the extension method use an Expando to associate the corresponding this object to the desired data:

extension JSList<T> on List<T> {
  static final _startValues = Expando<int>();

  int get start => _startValues[this] ?? 0;
  set start(int x) => _startValues[this] = x;
}

Note that Expando has some restrictions about what types can be used as the key. See the Expando documentation for more details.

  •  Tags:  
  • dart
  • Related