3

Is there a way to access static methods from a template in Dart?

Problem is as follows:

offer.dart:

class Offer {
  static String getPriceString(double price) {
    return euroFormat.format(price) + " €";
  }
}

First Try:

main_component.html:

<div class="offer" *ngFor="let offer of offers">
 <span class="offer_price">{{ offer.getPriceString(1.9) }}</span>
</div>

Exception:

EXCEPTION: NoSuchMethodError: Class 'Offer' has no instance method 'getPriceString'. Receiver: Instance of 'Offer' Tried calling: getPriceString(4.9)

Second Try:

main_component.html:

<div class="offer" *ngFor="let offer of offers">
 <span class="offer_price">{{ Offer.getPriceString(1.9) }}</span>
</div>

Exception 2:

EXCEPTION: NoSuchMethodError: Class 'MainComponent' has no instance getter 'Offer'. Receiver: Instance of 'MainComponent' Tried calling: Offer

If I remove the static keyword from getPriceString() everything works like called in "First Try" but it feels not nice because I lose the possibility for static call.

Blackbam
  • 17,496
  • 26
  • 97
  • 150

1 Answers1

3

The scope for binding expressions is the components class instance.

If you want to access something from outside that scope you need to provide a means to access it through the components class instance (like a getter)

class MyComponent {
  String get someStaticProp => SomeClass.someStaticProp;
}

then you can access it in view bindings like

<div>{{someStaticProp}}</div>
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • So there is now way to access it except if I extend the class with a possibility to access the property/method in a non-static manner? – Blackbam Mar 14 '17 at 17:55
  • 1
    Exactly. It's the same in TypeScript. I saw it mentioned that they consider allowing access to statics in TypeScript eventually. I can imagine that they'll add it to Dart as well when TypeScript supports it. – Günter Zöchbauer Mar 14 '17 at 17:58