[英]NoSuchMethod in dart?
Getting warning while trying to use noSuchMethod().尝试使用 noSuchMethod() 时收到警告。
The method missing isn't defined for the class Person.没有为类 Person 定义缺少的方法。
But according to the docs and other examples, whenever we call a non-existing member then, noSuchMethod() should be called.但是根据文档和其他示例,每当我们调用不存在的成员时,都应该调用 noSuchMethod()。 Whose default behavior is to throw noSuchMethodError.其默认行为是抛出 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}";
}
According to the official docs for invoking an unimplemented method, you have to satisfy one of the following points:根据调用未实现方法的官方文档,您必须满足以下几点之一:
Example 1 : Satifies Point First示例 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'
}
Example 2 : Satifies Point Second示例 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
}
Informal language specification: https://github.com/dart-lang/sdk/blob/master/docs/language/informal/nosuchmethod-forwarding.md 非正式语言规范: https : //github.com/dart-lang/sdk/blob/master/docs/language/informal/nosuchmethod-forwarding.md
tl;dr, you can only call methods that aren't implemented if: tl; dr,您只能在以下情况下调用未实现的方法:
The caller is of type dynamic The caller's super-types have that method that defined (even abstractly) Concretely, the following is no longer valid in Dart 2: 调用方的类型是动态的。调用方的超类型具有(甚至抽象地)定义的方法。具体来说,以下内容在Dart 2中不再有效:
@proxy class A { noSuchMethod(_) => 'Hello'; } main() { // Static analysis error, will refuse to build. print(new A().sayHello()); }
Refers to matanlurey explanation. 请参阅matanlurey说明。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.