在Dart中,库的使用时通过import关键字引入
library指令可以创建一个库,每个Dart文件都是一个库,即使没有使用library指令来指定。
name: xxx
description: A new flutter module project.
dependencies:
http: ^0.12.0+2
date_format: ^1.0.6
在当前目录新建lib文件夹 文件夹里新建Animal.dart文件
Anaimal.dart文件内容:
class Animal {
String _name;
int age;
Animal(this._name, this.age);
void printInfo() {
print("${this._name}------${this.age}");
}
// 定义一个共有方法 访问私有属性_name
String getName() {
return this._name;
}
// 定义一个私有方法
void _run() {
print('这是一个私有方法');
}
// 通过共有方法访问私有方法
execRun() {
this._run(); // 类里面方法的相互调用
}
}
主文件内容:
import 'lib/Animal.dart';
void main() {
Animal a = new Animal('小狗', 3);
print(a.getName()); // 小狗
}
import 'dart:math';
void main() {
print(min(12, 30)); // 12
}
import 'dart:io';
import 'dart:convert';
void main() async{
var result = await getDataFromZhihuAPI();
print(result);
}
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();
}
在当前目录新建pubspec.yaml文件
在pubspec.yaml文件 配置名称、描述、依赖等信息,内容如下:
name: xxx
description: A new flutter module project.
dependencies:
http: ^0.12.0+2
date_format: ^2.0.4
主文件内容:
import 'dart:convert' as convert;
import 'package:http/http.dart' as http;
main() async {
var url = "http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=1";
// Await the http get response, then decode the json-formatted responce.
var response = await http.get(url);
if (response.statusCode == 200) {
var jsonResponse = convert.jsonDecode(response.body);
print(jsonResponse);
} else {
print("Request failed with status: ${response.statusCode}.");
}
}
import 'package:date_format/date_format.dart';
main() async {
print(formatDate(DateTime(1989, 2, 21), [yyyy, '*', mm, '*', dd]));
}