代码之家  ›  专栏  ›  技术社区  ›  Shubhamhackz

dart中没有这样的方法?

  •  1
  • Shubhamhackz  · 技术社区  · 7 年前

    尝试使用noSuchMethod()时收到警告。

     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}";
    
     } 
    
    2 回复  |  直到 7 年前
        1
  •  5
  •   Shubhamhackz    7 年前

    根据调用未实现方法的官方文档,您必须满足以下几点之一:

    • 接收机为静态型动态型。
    • 接收器具有定义未实现方法的静态类型 (抽象是可以的),并且接收器的动态类型具有 noSuchMethod()的实现与类中的实现不同 对象

    例1:首先满足点

    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'
    }
    

    例2:满足第二点

    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
    }