Menu
Coddy logo textTech

noSuchMethod Override

Part of the Object Oriented Programming section of Coddy's Dart journey — lesson 74 of 110.

When you call a method that doesn't exist on an object, Dart normally throws a NoSuchMethodError. However, you can override the special noSuchMethod() method to intercept these calls and handle them gracefully.

To use noSuchMethod(), your class must also implement an interface or use dynamic typing.

The method receives an Invocation object containing details about the attempted call:

class Flexible {
  @override
  dynamic noSuchMethod(Invocation invocation) {
    var methodName = invocation.memberName.toString();
    print('Called: $methodName');
    return null;
  }
}

void main() {
  dynamic obj = Flexible();
  obj.anyMethod();      // Called: Symbol("anyMethod")
  obj.anotherOne(42);   // Called: Symbol("anotherOne")
}

The Invocation object provides useful information about the call - memberName gives you the method name as a Symbol, positionalArguments contains the arguments passed, and isMethod tells you if it was a method call versus a getter or setter.

class Logger {
  @override
  dynamic noSuchMethod(Invocation invocation) {
    print('Method: ${invocation.memberName}');
    print('Args: ${invocation.positionalArguments}');
    return 'handled';
  }
}

void main() {
  dynamic log = Logger();
  var result = log.save('data', 123);
  print(result);  // handled
}

This technique is useful for creating proxy objects, mock classes for testing, or building flexible APIs that respond to arbitrary method calls. However, use it sparingly since it bypasses compile-time type checking.

challenge icon

Challenge

Easy

Let's build a method logger that intercepts and records any method calls made on an object! You'll create a class that uses noSuchMethod() to capture information about undefined method calls and respond intelligently based on the method name.

You'll organize your code into two files:

  • method_logger.dart: Create a MethodLogger class that intercepts calls to undefined methods. Your logger should override noSuchMethod() to:
    • Extract the method name from the invocation (it will be a Symbol like Symbol("methodName") - you'll need to convert it to a string and extract just the name)
    • Print the method name and any positional arguments in this format: Called: [methodName] with args: [arguments]
    • Return a special response based on the method name:
      • If the method name contains get, return the string 'data retrieved'
      • If the method name contains save, return the string 'data saved'
      • Otherwise, return the string 'unknown action'
  • main.dart: Import your logger and demonstrate how it handles various undefined method calls. Remember to use dynamic typing so Dart allows calling methods that don't exist:
    • Create a MethodLogger instance using a dynamic variable
    • Call getUserData('Alice', 42) on it and print the returned result
    • Call saveRecord('important') on it and print the returned result
    • Call processItem() on it (no arguments) and print the returned result

To extract the method name from a Symbol, you can convert it to a string and then parse out the name between the quotes. For example, Symbol("myMethod").toString() gives you 'Symbol("myMethod")'.

Expected output:

Called: getUserData with args: [Alice, 42]
data retrieved
Called: saveRecord with args: [important]
data saved
Called: processItem with args: []
unknown action

Cheat sheet

The noSuchMethod() method allows you to intercept calls to methods that don't exist on an object. To use it, your class must use dynamic typing or implement an interface.

Override noSuchMethod() to handle undefined method calls:

class Flexible {
  @override
  dynamic noSuchMethod(Invocation invocation) {
    var methodName = invocation.memberName.toString();
    print('Called: $methodName');
    return null;
  }
}

void main() {
  dynamic obj = Flexible();
  obj.anyMethod();      // Called: Symbol("anyMethod")
  obj.anotherOne(42);   // Called: Symbol("anotherOne")
}

The Invocation object provides information about the call:

  • memberName - the method name as a Symbol
  • positionalArguments - the arguments passed to the method
  • isMethod - indicates if it was a method call versus a getter or setter
class Logger {
  @override
  dynamic noSuchMethod(Invocation invocation) {
    print('Method: ${invocation.memberName}');
    print('Args: ${invocation.positionalArguments}');
    return 'handled';
  }
}

void main() {
  dynamic log = Logger();
  var result = log.save('data', 123);
  print(result);  // handled
}

This technique is useful for creating proxy objects, mock classes for testing, or flexible APIs, but should be used sparingly as it bypasses compile-time type checking.

Try it yourself

import 'method_logger.dart';

void main() {
  // TODO: Create a MethodLogger instance using dynamic typing
  // Using dynamic allows calling methods that don't exist at compile time
  dynamic logger;
  
  // TODO: Call getUserData('Alice', 42) and print the result
  
  // TODO: Call saveRecord('important') and print the result
  
  // TODO: Call processItem() with no arguments and print the result
  
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming