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
EasyLet'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 aMethodLoggerclass that intercepts calls to undefined methods. Your logger should overridenoSuchMethod()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'
- If the method name contains
- Extract the method name from the invocation (it will be a Symbol like
main.dart: Import your logger and demonstrate how it handles various undefined method calls. Remember to usedynamictyping so Dart allows calling methods that don't exist:- Create a
MethodLoggerinstance 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
- Create a
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 actionCheat 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 SymbolpositionalArguments- the arguments passed to the methodisMethod- 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
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesLibraries & ImportsIntroduction to OOPClasses vs ObjectsThe this KeywordMethodsInstance VariablesConstructor BasicsRecap - Simple Calculator4Null Safety
Intro to Null SafetyNullable vs Non-NullableThe ? and ! OperatorsLate Keyword & Null SafetyNull-Aware OperatorsNull Safety in ClassesRecap - User Profile System7Abstract Classes & Interfaces
Abstract ClassesAbstract MethodsInterfaces in DartImplicit InterfacesImplementing vs ExtendingMultiple InterfacesRecap - Shape Calculator10Collections & Generics
List, Set, Map OverviewType-Safe CollectionsGeneric ClassesGeneric MethodsGeneric ConstraintsIterable & IteratorRecap - Generic Storage13Advanced OOP Concepts
Composition vs InheritanceExtension MethodsCallable ClassesSealed Classes (Dart 3)Records (Dart 3)Patterns & Matching (3.0)Enums with Methods16Project: Library Management
Project OverviewBook and User Classes2Constructors in Dart
Default ConstructorNamed ConstructorsInitializer ListsConstant ConstructorsFactory ConstructorsRedirecting ConstructorsRecap - Shape Builder5Encapsulation
Public vs Private MembersThe _ Prefix ConventionLibrary-Level PrivacyGetters & Setters DepthInformation HidingRecap - Student Records8Mixins
Introduction to MixinsCreating MixinsUsing Multiple Mixinson Keyword in MixinsMixin vs InheritanceMixin vs InterfaceRecap - Animal System11Special Methods
toString() OverridehashCode & == OverrideComparable Interfacecall() MethodnoSuchMethod OverrideRecap - Custom Collection14Design Patterns Part 1
Intro to Design PatternsSingleton PatternFactory PatternObserver PatternStrategy Pattern3Class Properties
Instance vs Static MembersFinal & Const FieldsLate VariablesStatic Methods & FieldsGetters and SettersRecap - Bank Account Manager6Inheritance
Basic InheritanceThe super KeywordMethod OverridingThe @override AnnotationThe final Class KeywordConstructors & InheritanceRecap - Employee Hierarchy9Polymorphism
Polymorphism BasicsPolymorphism via InterfacesRuntime Type CheckingThe is & as OperatorsCovariant KeywordRecap - Payment Processor