Home > Software design >  Why Dart extension methods don't work for Image class
Why Dart extension methods don't work for Image class

Time:12-04

Hi people I'm facing a simple problem, I have this small code and doesn't work

extension ImageExt on Image {
  static Image base64(String encode, {double? width, double? height}) {
  final reserveWord = 'base64,';
  final codePart = encode.contains(reserveWord)
    ? encode.substring(encode.indexOf(reserveWord)   reserveWord.length)
    : encode;

  return Image.memory(base64Decode(codePart), width: width, height: height);
}

}

And when I try to use the autocomplete of VSCode, the method doesn't exist. VSCode

I include at the top of the file the import statement pointing at the correct file where my extension is defined. So I can't figure out what's wrong, please any help here will be appreciated. At the same file exists other extensions in these cases to String and Map types and work fine.

CodePudding user response:

You can call base64 on ImageExt like ImageExt.base64('...', width: 24, height: 24);. Currently static members on extensions are only accessible in the namespace of the extension itself (in this case ImageExt not Image).

You might be interested in reading this feature request submitted a while back on the dart language repo asking for static extension methods to be changed to support this. https://github.com/dart-lang/language/issues/723

  • Related