尝试使用 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}";
}
Run Code Online (Sandbox Code Playgroud)
根据调用未实现方法的官方文档,您必须满足以下几点之一:
示例 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'
}
Run Code Online (Sandbox Code Playgroud)
示例 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
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3168 次 |
| 最近记录: |