Reni Delonzek
Reni Delonzek

Reputation: 51

How to use extensions in dart

It was recently released in Dart 2.6 the extensions feature. I would like to be testing it and I made the following code

extension on DateTime {
    String string(String pattern) {
       try {
          return new DateFormat(pattern).format(this);
       } catch (e) {
          return null;
       }
    }
 }

I can call DateTime.now().string('dd'); in the same file where I create the extension quietly, however, I can't make the same call in any other function outside of that file. What am I doing wrong and how is it right to use them?

Upvotes: 3

Views: 3840

Answers (2)

Solen Dogan
Solen Dogan

Reputation: 149

Extensions are very powerful, as said power comes with great responsibility. Extending a double to parse celsius into fathrenheit. if you are using an external library especially

extension ExtendedDouble on double {
  // note: `this` refers to the current value
  double celsiusToFarhenheit() => this * 1.8 + 32;
  double farhenheitToCelsius() => (this - 32) / 1.8;
  String formatWithExtension()=>this.toStringAsFixed(2);
}

And you import this

Upvotes: -2

Andrey Gordeev
Andrey Gordeev

Reputation: 32449

Just give your extension a name and you're good:

extension MyExtension on DateTime {
    String string(String pattern) {
       try {
          return new DateFormat(pattern).format(this);
       } catch (e) {
          return null;
       }
    }
 }

Upvotes: 6

Related Questions