库-自定义库_系统库_第三方库
库-自定义库/系统库/第三方库
库-自定义库_系统库_第三方库
库-自定义库/系统库/第三方库
在Dart中 库的使用是通过import关键字引入。
library指定可以创建一个库,每个dart文件都是一个库,即使没有使用library指令来指定。
自定义库
import 'lib/xxx.dart'
系统内置库
import 'dart:math'
import 'dart:io'
import 'dart:convert'
1
2
3
4
5
6
import 'dart:math';
main() {
// 求最小数
print(min(12, 23)); // 12
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import 'dart:io';
import 'dart:convert';
void main() async{
var result = getData();
print(result);
}
getData() async {
// 1、创建 httpClinet 对象
var httpClient = new HttpClint();
// 2、创建 Uri 对象
var uri = new Uri.http('news-at.zhihu.com', '/api/3/stories/latest');
// 3、发起请求,等待请求
var request = await httpClient.geturl(uri);
// 4、关闭请求,等待响应
var response = await request.close();
// 5、解码响应内容
return await response.transform(utf8.decoder).join()'
}
Pub包管理系统中的库
https://pub.dev/packages
https://pub.flutter-io.cn/packages
https://pub.dartlang.org/flutter/
- 需要在自己的项目根目录新建一个
pubspec.yaml - 在
pubspec.yaml文件 然后配置名称、描述、依赖等信息 - 然后运行
pub get获取包下载到本地 - 项目中引入
import 'package:htt/http.dart' as http;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 重命名为 http
import 'package:http/http.dart' as http;
void main() async {
var result = getData();
print(result);
}
getData() async {
var url = Uri.https('news-at.zhihu.com', 'whatsit/create');
var response = await http.post(url, body: {'name': 'doodle', 'color': 'blue'});
print('Response status: ${response.statusCode}');
print('Response body: ${response.body}');
print(await http.read(Uri.https('example.com', 'foobar.txt')));
}
async 和 await
1
2
3
4
5
6
7
8
void main() async {
var result = await testAsync();
print(result); // hello
}
testAsync() async {
return 'hello';
}
解决同名库引用 - as
1
2
3
4
5
6
7
8
import 'paceage:lib/lib1.dart';
import 'paceage:lib2/lib2.dart' as lib;
main() {
Person p1 = new Person();
lib.Person = new lib.Person();
}
部分导入 - show/hide
1
2
3
4
5
6
7
8
9
10
11
void getSex() {
}
void getName() {
}
void getAge() {
}
1
2
3
4
5
6
7
8
import 'lib/myMath.dart' show getName;
// 隐藏 getName
// import 'lib/myMath.dart' hide getName;
void main() {
getName();
}
延迟加载
……
本文由作者按照 CC BY 4.0 进行授权