从Dart中的另一个文件导入扩展方法 [英] Import extension method from another file in Dart

查看:135
本文介绍了从Dart中的另一个文件导入扩展方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Dart 2.6中,我可以使用类似这样的扩展方法:

With Dart 2.6, I can use extension methods like this :

extension on int {
  int giveMeFive() {
    return 5;
  }
}


main(List<String> arguments) async {
  int x;
  x.giveMeFive();
}

一切正常! :D

但是现在,如果我想将扩展方法放在这样的另一个文件中:

But now if I want to put my extension method in another file like this :

main.dart

import 'package:untitled5/Classes/ExtendInt.dart';

main(List<String> arguments) async {
  int x;
  x.giveMeFive();
}

ExtendInt.dart

extension on int {
  int giveMeFive() {return 5;}
}

它失败并显示令人沮丧的错误..

It fails with a depressing error ..

bin/main.dart:9:5: Error: The method 'giveMeFive' isn't defined for the class 'int'.
Try correcting the name to the name of an existing method, or defining a method named 'giveMeFive'.
  x.giveMeFive();
    ^^^^^^^^^^

是否不允许这样做还是我做错了什么?
感谢您的阅读! :)

Is it not allowed to do that or am I doing something wrong ? Thanks for reading ! :)

推荐答案

这已按预期工作。没有名称的扩展名将隐式地赋予一个新名称,但它是私有的。因此,如果要在声明了扩展名的库外使用扩展名,则需要为其命名。

This is working as intended. An extension with no name is implicitly given a fresh name, but it is private. So if you want to use an extension outside the library where it is declared you need to give it a name.

这对用户也很有帮助,因为他们可能需要请使用其名称,以便能够解决冲突并在给定接收器类型有多个扩展提供GiveMeFive的扩展中,从您的扩展中显式地请求扩展方法GiveMeFive。

This is also helpful for users, because they may need to use its name in order to be able to resolve conflicts and explicitly ask for the extension method giveMeFive from your extension when there are multiple extensions offering a giveMeFive on the given receiver type.

因此您需要执行以下操作

So you need to do something like

extension MyExtension on int {
  int giveMeFive() => 5;
}

这篇关于从Dart中的另一个文件导入扩展方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆