在尝试使用noSuchMethod()时收到警告。
没有为Person类定义缺少的方法。
但是根据文档和其他示例,每当我们调用不存在的成员时,都应调用noSuchMethod()。谁的默认行为是抛出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}";
}
答案 0 :(得分:1)
根据用于调用未实现方法的官方文档,您必须满足以下条件之一:
示例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
}
答案 1 :(得分:0)
非正式语言规范: https://github.com/dart-lang/sdk/blob/master/docs/language/informal/nosuchmethod-forwarding.md
tl; dr,您只能在以下情况下调用未实现的方法:
呼叫者是动态类型呼叫者的超类型具有 具体定义的方法(甚至是抽象的),以下为否 在Dart 2中不再有效:
isCancelled
请参阅matanlurey的说明。