Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static extension functions not work in Dart

Tags:

flutter

dart

I want a static extension function. I've created one, it does not work. I've copied one from a tutorial, it works.

Why does the copied function work on my function does not?

This is the extension

extension DateTimeExtension on DateTime {
  String toDbDate() {
    return DbService.dtFormat.format(this);
  }

  static DateTime parseDbDate(String dbDate) {
    return DbService.dtFormat.parse(dbDate);
  }
}

// extension from tutorial I followed works
extension ShapeBorderX on ShapeBorder {
  static ShapeBorder roundedRectangle(double radius) {
    return RoundedRectangleBorder(
      borderRadius: BorderRadius.all(
        Radius.circular(radius),
      ),
    );
  }
}

And this is how I use it

  method() {
    DateTime.now().toDbDate();           // works
    DateTime.parseDbDate("2020-02-01");  // does not work
    ShapeBorderX.roundedRectangle(12.0); // works
  }

Clearly I'm doing something wrong, but I can't figure out what..

Thanks for your help.

like image 357
David Holkup Avatar asked Dec 29 '25 12:12

David Holkup


1 Answers

Ok, I see it now.

I have to call the method on the extension not on the class it extends.

DateTimeExtension.parseDbDate(...) works fine.

like image 100
David Holkup Avatar answered Jan 01 '26 03:01

David Holkup