Home > database >  Flutter: extension methods aren't recognized
Flutter: extension methods aren't recognized

Time:08-02

I'm trying to add extension method to BorderRadius which apply rounded corner to a container the extention code:

extension on BorderRadius{
  static get r10 => const BorderRadius.all(Radius.circular(10));
}

and here is how I used it on the container:

Container(
        alignment: Alignment.center,
        width: width * 0.7,
        padding: EdgeInsets.only(top: 20, bottom: 20),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.r10,
            gradient: LinearGradient(
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
                colors: [_buttonColor, Colors.purple]),
            boxShadow: const [
              BoxShadow(color: Colors.black87, blurRadius: 5)
            ]),
        child: Text(_lable))

The problem is the r10 method is not among the suggestions of the BorderRadius class and isn't recognized.

CodePudding user response:

You are using extension on BorderRadius. In order to use on value. you need to provide BorderRadius 1st, then you will be able to use it.

Like here using on zero BorderRadius.

  borderRadius: BorderRadius.zero.r10,
extension on BorderRadius {
  BorderRadius get r10 => const BorderRadius.all(Radius.circular(10));
}

Now as way you where using, you can create a custom class and static variable.

class MyBorderRadius {
 static BorderRadius get r10 => const BorderRadius.all(Radius.circular(10));
}

And use case

borderRadius: MyBorderRadius.r10,

CodePudding user response:

This extension is private which means you can't use it from outside the file where you created it.

To make it global, this is what you need to do

extension BorderRadiusExt on BorderRadius {
   static get r10 => const BorderRadius.all(Radius.circular(10));
}

You can't import something that is private and be able to use it. This you have here is an anonymous extension.

To learn more refer to this article.

https://wilsonwilson.dev/articles/dart-extension-methods

  • Related