一 概述
前面介绍Dart基础知识的时候基本上都是在一个文件里面编写Dart代码的,但实际开发中不可能这么写,模块化很重要,所以这就需要使用到库的概念。
在Dart中,库的使用时通过import关键字引入的。
library指令可以创建一个库,每个Dart文件都是一个库,即使没有使用library指令来指定。
Dart中的库主要有三种:
1、我们自定义的库
import 'lib/xxx.dart';
2、系统内置库
import 'dart:math';
import 'dart:io';
import 'dart:convert';
3、Pub包管理系统中的库
https://pub.flutter-io.cn/packages
https://pub.dartlang.org/flutter/
1、需要在自己想项目根目录新建一个pubspec.yaml
2、在pubspec.yaml文件 然后配置名称 、描述、依赖等信息
3、然后运行 pub get 获取包下载到本地
4、项目中引入库 import 'package:http/http.dart' as http; 看文档使用
import "student.dart"; // 自定义的库
import 'dart:math'; // 系统内置的库
import 'dart:io'; // 系统内在的库 实现网络请求
import 'dart:convert'; // 转换
getDataFromZhiHu() async {
/**
async和await
这两个关键字的使用只需要记住两点:
只有async方法才能使用await关键字调用方法
如果调用别的async方法必须使用await关键字
async是让方法变成异步。
await是等待异步方法执行完成。
* */
// 1 创建HttpClient 请求对象
HttpClient client = new HttpClient();
// 2 创建URI 对象
var uri = new Uri.http("news-at.zhihu.com", "/api/3/stories/latest");
// 3 发起请求
var req = await client.getUrl(uri);
// 4 关闭请求 等待响应
var response = await req.close();
// 5 解码响应的内容
return await response.transform(utf8.decoder).join();
}
void main() async {
// 1 调用自定义的库
Student s = Student();
s.getInfo();
// 2 系统内置的库
print(max(8, 13));
// 开平方
print(sqrt(25));
// 请求数据
var result = await getDataFromZhiHu();
print(result);
// 3 第三方的库
runApp(const MyApp());
}
二 引入第三方的库
从下面网站中找到自己需要的第三方库 ,看实例怎么使用
创建一个pubspec.yaml文件,内容如下
name: xxx
description: A new flutter module project.
dependencies:
http: ^0.12.0+2
date_format: ^1.0.6
https://pub.flutter-io.cn/packages
import 'dart:convert' as convert; // 转换
import 'package:http/http.dart' as http;
getDataFromZhiHuWithHttp() async {
var url = Uri.https("news-at.zhihu.com", "/api/3/stories/latest");
var response = await http.get(url);
if (response.statusCode == 200) {
var jsonResponse = convert.jsonDecode(response.body);
print(jsonResponse);
} else {
print(response.statusCode);
}
}