dartthiswarningsextension-methods

Dart extension: don't access members with 'this' unless avoiding shadowing


I'm learning to use the new Dart extension methods.

I'm doing this:

extension StringInsersion on StringBuffer {

  void insertCharCodeAtStart(int codeUnit) {
    final end = this.toString();
    this.clear();
    this.writeCharCode(codeUnit);
    this.write(end);
  }

  int codeUnitAt(int index) {
    return this.toString().codeUnitAt(index);
  }
}

So that I can do something like this:

myStringBuffer.insertCharCodeAtStart(0x0020);
int value = myStringBuffer.codeUnitAt(2);

However, I get the following lint warning:

Don't access members with this unless avoiding shadowing.

Should I be doing something different?


Solution

  • The warning you received means the following:
    There is no need to reference the current instance using keyword this. Everything will work without reference to the current instance because the static extension method itself acts as an instance method of extensible type.

    Simply put, just remove the reference to the current instance from your code.

    From this:

    final end = this.toString();
    

    To this:

    final end = toString();