Book Image

DART Cookbook

By : Ivo Balbaert
Book Image

DART Cookbook

By: Ivo Balbaert

Overview of this book

Table of Contents (18 chapters)
Dart Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Using noSuchMethod


When a method is called on an object, and this method does not exist in its class, or any of its superclasses in the inheritance tree, then noSuchMethod() from Object is called. The default behavior of noSuchMethod is to throw a NoSuchMethodError, method not found: 'methodname'. However, Dart can do more; as in some other dynamic languages, every class can implement noSuchMethod to make its behavior more adaptive and flexible. This is because of the fact that Dart is dynamically typed, so it is possible to call a method that does not exist in a dynamic variable. In Java, you get a compile time error for this. In Dart too, an error is thrown but at runtime. By using noSuchMethod(), we can circumvent this and put it to our use.

How to do it...

See noSuchMethod in action in the nosuchmethod project:

void main() {
  var embr = new Embrace(5);
  print(embr.missing("42", "Julia")); // is a missing method!
}

@proxy
class Embrace {
  // see code in previous recipes
  @override
...