自定義庫
我們可以将一組功能提取成一個獨立的dart檔案,這就是dart的自定義庫。
系統内置庫

第三方庫
我們可以從下面網址找到要用的庫:
https://pub.dev/packages
https://pub.flutter-io.cn/packages
https://pub.dartlang.org/flutter/
複制
找到對應的庫之後,我們首先建立一個pubspec.yaml檔案,内容如下:
name: xxx
description: A new flutter module project.
dependencies:
http: ^0.12.0+2
date_format: ^1.0.6
複制
然後将所需導入的庫的資訊配置到dependencies。
然後在終端運作 pub get 指令擷取遠端庫。
然後看文檔引入庫進行使用。
引入庫的沖突
當引入的兩個庫具有相同的名稱辨別符的時候,會造成沖突。這個時候就可以使用as關鍵字來指定庫的字首。
比如,Person1.dart檔案中定義了Person類:
class Person{
String name;
int age;
//預設構造函數的簡寫
Person(this.name,this.age);
Person.setInfo(String name,int age){
this.name=name;
this.age=age;
}
void printInfo(){
print("Person1:${this.name}----${this.age}");
}
}
複制
Person2檔案中也定義了Person類:
class Person{
String name;
int age;
//預設構造函數的簡寫
Person(this.name,this.age);
Person.setInfo(String name,int age){
this.name=name;
this.age=age;
}
void printInfo(){
print("Person2:${this.name}----${this.age}");
}
}
複制
然後在某檔案中同時引入Person1.dart和Person2.dart的時候就會導緻沖突。這是就可以給其中一個庫檔案指定字首:
import 'lib/Person1.dart';
import 'lib/Person2.dart' as lib;
複制
然後使用如下:
main(List<String> args) {
Person p1=new Person('張三', 20);
p1.printInfo();
lib.Person p2=new lib.Person('李四', 20);
p2.printInfo();
}
複制
部分導入
如果我們隻需要導入庫的一部分,那麼有兩種方式:
方式一:隻導入需要的部分,使用show關鍵字,如下例:
import 'package:lib1/lib1.dart' show foo;
複制
方式二:隐藏不需要的部分,使用hide關鍵字,如下例:
import 'package:lib2/lib2.dart' hide foo;
複制
以上