Q:

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?

A:

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;
       }
    }
 }

