5

Getting warning while trying to use noSuchMethod().

The method missing isn't defined for the class Person.

But according to the docs and other examples, whenever we call a non-existing member then, noSuchMethod() should be called. Whose default behavior is to throw noSuchMethodError.

 void main() {
    var person = new Person();
    print(person.missing("20", "Shubham")); // is a missing method!
 }

 class Person {

    @override
    noSuchMethod(Invocation msg) => "got ${msg.memberName} "
                      "with arguments ${msg.positionalArguments}";

 } 
Shubhamhackz
  • 7,333
  • 7
  • 50
  • 71

1 Answers1

9

According to the official docs for invoking an unimplemented method, you have to satisfy one of the following points:

  • The receiver has the static type dynamic.
  • The receiver has a static type that defines the unimplemented method (abstract is OK), and the dynamic type of the receiver has an implemention of noSuchMethod() that’s different from the one in class Object.

Example 1 : Satifies Point First

class Person {
  @override  //overring noSuchMethod
    noSuchMethod(Invocation invocation) => 'Got the ${invocation.memberName} with arguments ${invocation.positionalArguments}';
}

main(List<String> args) {
  dynamic person = new Person(); // person is declared dynamic hence staifies the first point
  print(person.missing('20','shubham'));  //We are calling an unimplemented method called 'missing'
}

Example 2 : Satifies Point Second

class Person {
  missing(int age,String name);

  @override //overriding noSuchMethod
    noSuchMethod(Invocation invocation) => 'Got the ${invocation.memberName} with arguments ${invocation.positionalArguments}';
}

main(List<String> args) {
  dynamic person = new Person(); //person could be var, Person or dynamic
  print(person.missing(20,'shubham')); //calling abstract method
}
Shubhamhackz
  • 7,333
  • 7
  • 50
  • 71