Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the dart equivalent to Swift “extensions”?

Keyword/reserved word extension allow code to be much cleaner by using an existing class in the standard frameworks without subclassing them. Is there a keyword in Dart that allows the same behavior?

extension Double {
    var mm: Double { return self / 1_000.0 }
}

let oneInch = 25.4.mm
print("One inch is \(oneInch) meters")
like image 864
Marco Leong Avatar asked Jan 01 '23 05:01

Marco Leong


2 Answers

They are finally here 🥳

From dart version 2.6 (not 100% sure).

class Foo {
  printFoo()  {
    print("Foo");
  }
}

extension Bar on Foo { 
  printBar()  {
    print("Bar");
  }
}

void main() {
  final foo = Foo();
  foo.printFoo();
  foo.printBar();
}

prints:

Foo

Bar

You can give it a try in dart pad.

like image 94
Durdu Avatar answered Jan 03 '23 18:01

Durdu


Extension methods are currently being implemented into the language.

https://github.com/dart-lang/language/projects/1#card-18758939

Specifications document

https://github.com/dart-lang/language/blob/master/accepted/future-releases/static-extension-methods/feature-specification.md

like image 41
Jaja Harris Avatar answered Jan 03 '23 18:01

Jaja Harris