Extension method on a class without a constructor in dart?

48 Views Asked by At

I've written extension methods on lots of dart stuff, but when I tried to do it FontWeight from dart:ui it isn't recognized as legit.

extension FontWeightExtension on FontWeight {
  static const FontWeight thin = FontWeight.w100;
  static const FontWeight extraLight = FontWeight.w200;
  static const FontWeight light = FontWeight.w300;
  static const FontWeight regular = FontWeight.w400;
  static const FontWeight medium = FontWeight.w500;
  static const FontWeight semiBold = FontWeight.w600;
  static const FontWeight extraBold = FontWeight.w800;
  static const FontWeight thick = FontWeight.w900;
}

then

import 'package:my_package/utils/extensions.dart';
FontWeight.medium...

the linter gives me this error:

The getter 'medium' isn't defined for the type 'FontWeight'. Try importing the library that defines 'medium', correcting the name to the name of an existing getter, or defining a getter or field named 'medium'.

So I thought the static thing was messing it up so I tried it without static and got the same issue.

But check this out:

FontWeight().medium

now I get two errors:

The class 'FontWeight' doesn't have a default constructor. Try using one of the named constructors defined in 'FontWeight'

Of course, but I also get this:

Static field 'medium' can't be accessed through an instance. Try using the class 'FontWeightExtension' to access the field.

So it knows about the extension method, but I can't use it on FontWeight

Is there anyway to get around this? How do you write an extension method on a class that doesn't have a constructor?

0

There are 0 best solutions below