标签:移动 命名空间 div 语言 最低要求 创建 三方 none 就是
通过import语句在一个库中引用另外一个库的文件。需要注意以下事项
import的例子如下:
import ‘dart:io‘; import ‘package:mylib/mylib.dart‘; import ‘package:utils/utils.dart‘; void main(List<String> args){
}
当引用的库拥有相互冲突的名字,可以为其中一个或者几个指定不一样的前缀。这与命名空间的概念比较接近
void hello() { print(‘test2.dart : hello()函数‘); }
test3.dart代码如下:
void hello(){ print(‘test3.dart : hello()函数‘); }
现在要在test1.dart中导入这两个文件:
//报错写法:
import ‘test2.dart‘;
import ‘test3.dart‘;
//正确写法:
import ‘test2.dart‘;
import ‘test3.dart‘ as test3; // 给导入的库指定一个前缀 方便识别
//调用方式:
void main(){
hello();//test2.dart : hello()函数
test3.hello();//test3.dart : hello()函数
}
总结:
test1 与 test3 都拥有hello()函数重复的部分,如果直接引用就不知道具体引用哪一个hello(), 所以代码中用as关键词把 ‘test3.dart’指定成了 test3. 这样就不会冲突了。
库与文件类,在引用时冲突的处理方法,和文件与方法在引用时冲突处理方法抑制。
如果只想使用库的一部分,则可以有选择地导入库,可以使用show或者hide关键字。
// 仅导入mylib.dart里面的test2函数 import ‘libs/mylib1.dart‘ show test2; // 刚好和show相反 除了test2函数之外 其它的都导入 import ‘libs/mylib2.dart‘ hide test2;
延迟加载(也称为延迟加载)
允许应用程序根据需要加载库,如果需要的话。以下是您可能使用延迟加载的一些情况:
deferred as
它导入一个库。当我们import一个库的时候,如果使用了as 不能同时使用deferred as
// import ‘libs/mylib.dart‘; // 不能同时使用 import ‘libs/mylib.dart‘ deferred as tests;
当您需要库时,使用库的标识符调用loadLibrary()。 例如(注意导包:import ‘dart:async‘;)
Future hello() async { await tests.loadLibrary(); tests.test2(); }
// 然后再去使用: void main(){ hello(); // 结果是: mylib.dart:test2()函数 }
在上述的代码中,await关键字暂停执行,直到库被加载。 您可以在一个库上调用loadLibrary()多次,而不会出现问题。该库只加载一次。
使用延迟加载时请记住以下内容:
【说明】dart官网不推荐使用part ,这个仅作为了解。 使用part指令,可以将库拆分为多个Dart文件。part of表示隶属于某个库的一部分。
【注意事项】
// library testlib2; 这个不能和part of同时使用 会报错 // part of 表示这个库是testlib库的一部分 part of testlib1;
part of testlib1
; 表示testlib2这个库是testlib库的yi部分。// 第1个库: library testlib1; // 可以不写 part ‘testlib2.dart‘; void run() { print(‘testlib1库 : run()函数‘); }
part of testlib1; class testLib2 {} void start() { print(‘testlib2库 : start()函数‘); }
// 第1个库: library testlib1; // 可以不写 part ‘testlib2.dart‘;
// 这是一个库 命名为mylib library mylib; // 希望使用mylib的时候 自动使用otherlib.dart 可以使用export关键字引入其他库 export ‘otherlib.dart‘; // 导入otherlib2.dart export ‘otherlib2.dart‘; class MyLib { void test() { print(‘mylib.dart: MyLib : test()函数‘); } } void test2() { print(‘mylib.dart: test2()函数‘); }
// otherlib库 library otherlib; class otherLib {} void test() { print(‘otherLib库 : test()函数‘); }
// otherlib2库 library otherlib2; class otherLib2 {} void test2() { print(‘otherLib2库 : test2()函数‘); }
pubspec.yaml
文件和lib
目录。 标签:移动 命名空间 div 语言 最低要求 创建 三方 none 就是
原文地址:https://www.cnblogs.com/lxlx1798/p/11018884.html