1、需要在自己想项目根目录新建一个pubspec.yaml
2、在pubspec.yaml文件 然后配置名称 、描述、依赖等信息
3、然后运行 pub get 获取包下载到本地
4、项目中引入库 import 'package:http/http.dart' as http; 看文档使用
// 使用自定义库
// lib/Animal.dart
class Animal {
String _name; //私有属性
int age;
//默认构造函数的简写
Animal(this._name, this.age);
void printInfo() {
print("${this._name}----${this.age}");
}
String getName() {
return this._name;
}
void _run() {
print('这是一个私有方法');
}
execRun() {
this._run(); //类里面方法的相互调用
}
}
import 'lib/Animal.dart';
main() {
var a = new Animal('小黑狗', 20);
print(a.getName());
}
// 内置库httpClient请求数据
import 'dart:io';
import 'dart:convert';
void main() async {
var result = await getDataFromZhihuAPI();
print(result);
}
//api接口: <http://news-at.zhihu.com/api/3/stories/latest>
getDataFromZhihuAPI() async {
//1、创建HttpClient对象
var httpClient = new HttpClient();
//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();
}