dart语法
1. Dart是代码类型安全的语言,但可用var定义而不用显示指定
2. Dart的流程控制语句
if...else if
for (final item in items)
while()
3. Dart建议为每个函数参数和返回值都指定类型
4. 胖箭头 => 用于仅包含一条语句的函数,该语法在将匿名函数作为参数传递时很有用
5. 注释 //单行注释 ///文档注释 /**/多行注释
6. 类 class
class MyClass{
String name;
int? age;
int? get sex => age?.sign;//只读属性
MyClass(this.name,this.age){//构造函数
}
MyClass.namedConstructor(String name):this(name,null);//命名构造函数
void printGo(){//函数
print("name:$name");
var agee = this.age;
var sexx = this.sex;
}
}
7. 枚举类型 Enum
enum PlanetType { terrestrial, gas, ice }
增强型枚举(无法在外部实例化)
enum Planet {
mercury(planetType: PlanetType.terrestrial, moons: 0, hasRings: false),
venus(planetType: PlanetType.terrestrial, moons: 0, hasRings: false),
// ···
uranus(planetType: PlanetType.ice, moons: 27, hasRings: true),
neptune(planetType: PlanetType.ice, moons: 14, hasRings: true);
/// A constant generating constructor
const Planet(
{required this.planetType, required this.moons, required this.hasRings});
/// All instance variables are final
final PlanetType planetType;
final int moons;
final bool hasRings;
/// Enhanced enums support getters and other methods
bool get isGiant =>
planetType == PlanetType.gas || planetType == PlanetType.ice;
}
8. Dart支持单继承 extends
9. Mixins 在多个类层次结构中重用代码 with
10. 接口和抽象类
所有的类都隐式定义成了一个接口 implements
抽象类 abstract class
11. 异步
async...await
async*...await生成流
Stream<String> report(Spacecraft craft, Iterable<String> objects) async* {
for (final object in objects) {
await Future.delayed(oneSecond);
yield '${craft.name} flies by $object';
}
}
12. 异常
throw
捕获异常
try{...}on IOException catch (e){...}finally{...}
13. 变量
//可变类型变量
Object name2 = "boo";
dynamic name3 = "boo";
//不可变类型变量
var name = "boo";//第一次赋值就把变量类型定了
String name4 = "boo";
14. 具有可空类型的未初始化变量的初始值为 null,即使是具有数值类型的变量,初始值也为空,因为数字(就像 Dart 中的其他所有东西一样)都是对象
15. 顶级变量和类变量是延迟初始化的,它们会在第一次被使用时再初始化
16. 延迟初始化变量 late ,使用这个变量时才会初始化,适应于以下变量
可能不需要该变量,并且初始化它的开销很高
初始化一个实例变量,它的初始化方法需要调用 this
17. 终值final 常量const
const是编译时常量,隐式包含final
实例变量可以是final但不能是const
final 对象不能被修改,但它的字段可能可以被更改
const 对象及其字段不能被更改:它们是 不可变的
18. as 类型转换 is 对象是否是指定类型 is! 对象是否不是指定类型
19. ??= 赋值运算符,如何对象不为空才赋值
20. 条件表达式
var visibility = isPublic ? 'public' : 'private';
String playerName(String? name) => name ?? 'Guest';//?? 判断是否为null
21. 级联表示法
var paint = Paint()
..color = Colors.black//给对象的属性赋值
..strokeCap = StrokeCap.round
..strokeWidth = 5.0;
querySelector('#confirm') // Get an object.
?..text = 'Confirm' // 使用?..判断对象是否为null
..classes.add('important')
..onClick.listen((e) => window.alert('Confirmed!'))
..scrollIntoView();
22. 导入库 import
如果导入两个具有冲突标识符的库,则可以为一个或两个库指定前缀
import 'package:lib1/lib1.dart';
import 'package:lib2/lib2.dart' as lib2;
Element element1 = Element();
lib2.Element element2 = lib2.Element();
如果指向使用库的一部分,则可以选择性的导入库
// Import only foo.
import 'package:lib1/lib1.dart' show foo;
// Import all names EXCEPT foo.
import 'package:lib2/lib2.dart' hide foo;
延迟加载库 deferred as
import 'package:greetings/hello.dart' deferred as hello;
使用(多次调用库仅加载一次)
Future<void> greet() async {
await hello.loadLibrary();
hello.printGreeting();
}
23.Dart内置类型
int ,double,String,bool,(value1,value2),List,Set,Map,Runescharacters,Symbol,Null,Object Enum,Future,Stream,Iterable,Never(最常用于始终引发异常的函数),dynamic(表示您要禁用静态检查),void
24.Dart内置类型的基本使用
num x = 1;//变量 可以同时具有 Integer 和 Double 值
int.parse('1'); double.parse('1.1'); //字符串转化成数字
1.toString(); 3.14159.toStringAsFixed(2);//数字转化成字符串
创建字符串的几种方式
var s1 = 'String '
'concatenation'
" works even over line breaks.";
var s2 = 'The + operator ' + 'works, as well.';
var s1 = '''
You can create
multi-line strings like this one.
''';
var s2 = """This is also a
multi-line string.""";
var s = r'In a raw string, not even \n gets special treatment.'; //在字符串前加上 :r防止反斜线转义
25.Dart的Records类型(需要3.0版本以上)
var record = ('first', a: 2, b: true, 'last');
(String, int) record;
({int a, bool b}) record;
26.Dart的集合类型
List(有序的对象组)
var list = [1, 2, 3];
编译时常量列表
var constantList = const [1, 2, 3]; // constantList[1] = 1; 这会报错
Set(无序的集合)
var halogens = {'fluorine', 'chlorine', 'bromine', 'iodine', 'astatine'};
创建空的集合
var names = <String>{};
// Set<String> names = {}; // 这样写也是可以的
// var names = {}; // 不加泛型的是map
Map
var gifts = {
// Key: Value
'first': 'partridge',
'second': 'turtledoves',
'fifth': 'golden rings'
};
var gifts = Map<String, String>();
27.对集合使用的运算符
var list = [1, 2, 3];
var list2 = [0, ...list];//数组拼接
var list2 = [0, ...?list];//list可能为null的数组拼接
var nav = ['Home', 'Furniture', 'Plants', if (promoActive) 'Outlet'];
var nav = ['Home', 'Furniture', 'Plants', if (login case 'Manager') 'Inventory'];
var listOfInts = [1, 2, 3];
var listOfStrings = ['#0', for (var i in listOfInts) '#$i'];
28.使用泛型的好处
减少代码重复
系统可以检测错误从而更好的生成代码
29.类型别名 Typedef
在 2.13 之前,typedef 仅限于函数类型。 使用新的 typedef 需要至少 2.13 的语言版本
typedef IntList = List<int>;
IntList il = [1, 2, 3];
typedef ListMapper<X> = Map<X, List<X>>;
Map<String, List<String>> m1 = {}; // Verbose.
ListMapper<String> m2 = {}; // Same thing but shorter and clearer.
建议对函数使用内联函数类型而不是 typedef
typedef Compare<T> = int Function(T a, T b);
30.Dart是类型安全的语言,使用静态类型检查和运行时检查组合,还有类型推断
31.模式 Patterns ???
模式要求语言版本至少为 3.0。
遍历map
Map<String, int> hist = {
'a': 23,
'b': 100,
};
for (var MapEntry(key: key, value: count) in hist.entries) {
print('$key occurred $count times');
}
32.函数对象 Function
命名函数
/// Sets the [bold] and [hidden] flags ...
enableFlags({bool? bold, bool? hidden}) {...}
/// Sets the [bold] and [hidden] flags ...
void enableFlags({bool bold = false, bool hidden = false}) {...}
const Scrollbar({super.key, required Widget child});
函数可选参数位
String say(String from, String msg, [String? device]) {
var result = '$from says $msg';
if (device != null) {
result = '$result with a $device';
}
return result;
}
将函数作为参数传递给另一个函数
void printElement(int element) {
print(element);
}
var list = [1, 2, 3];
// Pass printElement as a parameter.
list.forEach(printElement);
将函数分配给变量
var loudify = (msg) => '!!! ${msg.toUpperCase()} !!!';
assert(loudify('hello') == '!!! HELLO !!!');
匿名函数
const list = ['apples', 'bananas', 'oranges'];
var uppercaseList = list.map((item) {
return item.toUpperCase();
}).toList();
// Convert to list after mapping
for (var item in uppercaseList) {
print('$item: ${item.length}');
}
语法闭包,把函数作为返回值
/// Returns a function that adds [addBy] to the
/// function's argument.
Function makeAdder(int addBy) {
return (int i) => addBy + i;
}
void main() {
// Create a function that adds 2.
var add2 = makeAdder(2);
// Create a function that adds 4.
var add4 = makeAdder(4);
assert(add2(3) == 5);
assert(add4(3) == 7);
}
撕下,丢弃for循环获取值很有用
var charCodes = [68, 97, 114, 116];
var buffer = StringBuffer();
// Function tear-off
charCodes.forEach(print);
// Method tear-off
charCodes.forEach(buffer.write);
函数返回值
未指定返回默认返回null
如果要返回多个值
(String, int) foo() {
return ('something', 42);
}
延迟生成值序列
同步生成 sync*yield
Iterable<int> naturalsTo(int n) sync* {
int k = 0;
while (k < n) yield k++;
}
异步生成 async*yield
Stream<int> asynchronousNaturalsTo(int n) async* {
int k = 0;
while (k < n) yield k++;
}
如果需要递归 yield*
Iterable<int> naturalsDownFrom(int n) sync* {
if (n > 0) {
yield n;
yield* naturalsDownFrom(n - 1);
}
}
外部功能
external void someFunc(int i); 与其他语言互调的时候用到
33.循环
for (var i = 0; i < 5; i++) {} //带索引
for (final c in callbacks) {}//不带索引
var collection = [1, 2, 3];
collection.forEach(print); // 1 2 3 如果你使用的是 Iterable ->forEach方法
while (!isDone()) {}//在循环之前评估条件
do {printLine();} while (!atEndOfPage());//在循环后评估条件
while (true) { if (shutDownRequested()) break;}//中断循环
for (int i = 0; i < candidates.length; i++) {}//跳到下一个循环
candidates.where((c) => c.yearsExperience >= 5).forEach((c) => c.interview());//如果你使用的是 Iterable ,可以先where再forEach
34.分支
if (isRaining()) {} else if (isSnowing()) {} else {} // if...else
if (pair case [int x, int y]) return Point(x, y);//if...case
var command = 'OPEN';
switch (command) { //结束非空子句的其他有效方法是 continue、throw 或 return 语句
case 'CLOSED':
executeClosed();
case 'PENDING':
executePending();
case 'APPROVED':
executeApproved();
case 'DENIED':
executeDenied();
continue newCase;//还可以开启新的判断
newCase:
case 'OPEN':
executeOpen();
default:
executeUnknown();
}
//可以对switch语句进行返回值处理,需要dart3.0版本
switch (charCode) {
case slash || star || plus || minus:
token = operator(charCode);
default:
throw FormatException('Invalid');
}
转换成如下
token = switch (charCode) {
slash || star || plus || minus => operator(charCode),
_ => throw FormatException('Invalid')
};
穷举性检查:很适用枚举和密封类型(sealed修饰的类)的判断,比如判断是否是他的子类
sealed class Shape {}
class Square implements Shape {
final double length;
Square(this.length);
}
class Circle implements Shape {
final double radius;
Circle(this.radius);
}
double calculateArea(Shape shape) => switch (shape) {
Square(length: var l) => l * l,
Circle(radius: var r) => math.pi * r * r
};
35异常处理
Dart的异常不用在方法上声名
Dart提供了Exception和Error两种主要类型的异常,还有其他预定义的子类型,但是它可以抛出任何非null对象的类型作为异常
抛出异常:
throw FormatException('Expected at least 1 section');
throw 'Out of llamas!';
捕获异常
try {
breedMoreLlamas();
} on OutOfLlamasException {//捕获指定类型的异常
buyMoreLlamas();
} on Exception catch (e) {//捕获其他Exception类型的异常
print('Unknown exception: $e');
} catch (e) {//不指定类型,处理所有异常
print('Something really unknown: $e');
} catch (e, s) {//可以指定两个参数,第一个是引发的异常,第二个是堆栈跟踪(StackTrace对象)
print('Exception details:\n $e');
print('Stack trace:\n $s');
} catch (e) {
print('misbehave() partially handled ${e.runtimeType}.');
rethrow; // 还可以把捕获的异常又抛出给调用者
} finally {//不管匹配到了任何类型的异常都会运行这个条件语句
cleanLlamaStalls(); // Then clean up.
}
36类
Dart是面向对象的语言,具有基于class和mixin的继承,除了null ,都是继承自Object
构造函数
new 是可选关键字
构造两个相同的编译时常量只会生成一个实例
var a = const ImmutablePoint(1, 1);
var b = const ImmutablePoint(1, 1);
assert(identical(a, b)); // They are the same instance!
构造函数是常量的,但是没有使用const关键字也不能构建常量对象
var a = const ImmutablePoint(1, 1); // Creates a constant
var b = ImmutablePoint(1, 1); // Does NOT create a constant
assert(!identical(a, b)); // NOT the same instance!
获取运行时对象的类型
print('The type of a is ${a.runtimeType}');//测试环境使用
print('The type of a is ${a is Type}');//生产环境使用
实例变量声明
double initialX = 1.5;
class Point {
double? x; // 初始值为null的实例变量
double? y; // Declare y, initially null.
double z = 0; // 初始值为0的实例变量,不可为null的变量必须在声明时初始化
//所有实例变量都会生成一个隐式getter方法,非final实例变量和late final实例变量也会生成隐式setter方法
double? x = initialX;//这个是可以访问的
double? y = this.x;//这个无法访问
late double? z = this.x;//这个可以访问
final String org = 'CN';
//必须配合使用
final String name;
Point(this.name);
Point.unnamed() : name = '';//获取这样就不需要非要传值了
//也可以使用late final 表示实例值在构造函数运行之后赋值
late final String lang;
}
可以创建一个类去实现另外一个或多个类(必须要覆写里面的变量和方法)
class Point implements Comparable, Location {...}
类变量和方法
使用关键字 static
class Queue {
static const initialCapacity = 16;//静态变量在使用之前不会初始化
//一般使用顶级函数而不是静态方法
//静态方法可以用作编译时常量
static double distanceBetween(Point a, Point b) {
var dx = a.x - b.x;
var dy = a.y - b.y;
return sqrt(dx * dx + dy * dy);
}
}
37构造函数
const double xOrigin = 0;
const double yOrigin = 0;
class Point {
// Instance variables to hold the coordinates of the point.
double x;
double y;
// 生成式构造函数,在构造体返回之前初始化实例变量
Point(this.x, this.y);
//默认构造函数,没有参数和名称的生成式构造函数
//命名构造函数,子类不会继承超类的命名构造函数
Point.origin()
: x = xOrigin,
y = yOrigin;
//常量构造函数,生成不变的对象
final double x, y;
const ImmutablePoint(this.x, this.y);
//重定向构造函数,使用冒号定向
Point.alongXAxis(double x) : this(x, 0);
//工厂构造函数:缓存现有实例,而不是创建新实例;子类型的新实例
final String name;
bool mute = false;
static final Map<String, Logger> _cache = <String, Logger>{};
factory Logger(String name) {
return _cache.putIfAbsent(name, () => Logger._internal(name));
}
factory Logger.fromJson(Map<String, Object> json) {
return Logger(json['name'].toString());
}
Logger._internal(this.name);
void log(String msg) {
if (!mute) print(msg);
}
}
撕下tear-off
var strings = charCodes.map((code) => String.fromCharCode(code));
//当参数相同时可以这样写
var strings = charCodes.map(String.fromCharCode);
var buffers = charCodes.map((code) => StringBuffer(code));
var buffers = charCodes.map(StringBuffer.new);
38实例变量的初始化
在声明变量时进行初始化
class PointA {
double x = 1.0;
double y = 2.0;
// The implicit default constructor sets these variables to (1.0,2.0)
// PointA();
@override
String toString() {
return 'PointA($x,$y)';
}
}
使用初始化形式参数
class PointB {
final double x;
final double y;
// Sets the x and y instance variables
// before the constructor body runs.
PointB(this.x, this.y);
PointB.named({this.x = 1.0, this.y = 1.0});//也可使用这种写法
// 可选形式参数
PointB.optional([this.x = 0.0, this.y = 0.0]);
}
私有字段不能用作命名初始化正式形式。
class PointB {
PointB.namedPrivate({required double x, required double y})
: _x = x,
_y = y;
}
使用初始值设定项列表
在构造函数主体运行之前,您可以初始化实例变量。 用逗号分隔初始值设定项。
// Initializer list sets instance variables before
// the constructor body runs.
Point.fromJson(Map<String, double> json)
: x = json['x']!,
y = json['y']! {
print('In Point.fromJson(): ($x, $y)');
}
39构造函数继承
子类不会从父类继承构造函数,只能使用默认构造函数
非默认超类构造函数
class Person {
String? firstName;
Person.fromJson(Map data) {
print('in Person');
}
}
class Employee extends Person {
// Person does not have a default constructor;
// you must call super.fromJson().
Employee.fromJson(Map data) : super.fromJson(data) {//super调用必不可少
print('in Employee');
}
}
//由于 Dart 在调用构造函数之前会向超类构造函数计算参数,因此参数可以是类似于 函数调用
class Employee extends Person {
Employee() : super.fromJson(fetchDefaultData());//
}
Super参数
class Vector2d {
final double x;
final double y;
Vector2d(this.x, this.y);
}
class Vector3d extends Vector2d {
final double z;
// 下面两种方式时一样的效果
// Vector3d(final double x, final double y, this.z) : super(x, y);
Vector3d(super.x, super.y, this.z);
}
//还可以使用如下
class Vector2d {
Vector2d.named({required this.x, required this.y});
}
class Vector3d extends Vector2d {
final double z;
// Forward the y parameter to the named super constructor like:
// Vector3d.yzPlane({required double y, required this.z})
// : super.named(x: 0, y: y);//这两种方式等同
Vector3d.yzPlane({required super.y, required this.z}) : super.named(x: 0);
}
40.成员方法
基本定义
class Point {
final double x;
final double y;
Point(this.x, this.y);
double distanceTo(Point other) {
var dx = x - other.x;
var dy = y - other.y;
return sqrt(dx * dx + dy * dy);
}
}
声明运算符
class Vector {
final int x, y;
Vector(this.x, this.y);
Vector operator +(Vector v) => Vector(x + v.x, y + v.y);
Vector operator -(Vector v) => Vector(x - v.x, y - v.y);
@override
bool operator ==(Object other) =>
other is Vector && x == other.x && y == other.y;
}
void main() {
final v = Vector(2, 3);
final w = Vector(2, 2);
assert(v + w == Vector(4, 5));
assert(v - w == Vector(0, 1));
}
getter和setter
class Rectangle {
double left, top, width, height;
Rectangle(this.left, this.top, this.width, this.height);
// Define two calculated properties: right and bottom.
double get right => left + width;
set right(double value) => left = value - width;
double get bottom => top + height;
set bottom(double value) => top = value - height;
}
抽象方法
抽象方法只能存在于抽象类或 mixin 中
abstract class Doer {
void doSomething(); // Define an abstract method.
}
class EffectiveDoer extends Doer {
void doSomething() {
}
}
41扩展类
extends
class Television {
void turnOn() {
_ illuminateDisplay();
_ activateIrSensor();
}
}
class SmartTelevision extends Television {
void turnOn() {
super.turnOn();
_ bootNetworkInterface();
_ initializeMemory();
_ upgradeApps();
}
}
覆写noSuchMethod()方法
class A {
// Unless you override noSuchMethod, using a
// non-existent member results in a NoSuchMethodError.
@override
void noSuchMethod(Invocation invocation) {
print('You tried to use a non-existent member: '
'${invocation.memberName}');
}
}
42混入 mixin
使用
class Maestro extends Person with Musical, Aggressive, Demented {
Maestro(String maestroName) {}
}
声明:不能有extends和任何声明的构造函数
mixin Musical {
bool canPlayPiano = false;
void entertainMe() {
if (canPlayPiano) {
print('Playing piano');
}
}
}
在mixin中定义抽象成员
mixin Musician {
void playInstrument(String instrumentName); // Abstract method.
void playPiano() {
playInstrument('Piano');
}
}
class Virtuoso with Musician {
@override
void playInstrument(String instrumentName) { // Subclass must define.
print('Plays the $instrumentName beautifully');
}
}
访问mixin的子类中的state
//可以应用于具有 [name] 属性的任何类型的类型,并提供[hashCode] 和运算符 '==' 的实现
mixin NameIdentity {
String get name;
@override
int get hashCode => name.hashCode;
@override
bool operator ==(other) => other is NameIdentity && name == other.name;
}
class Person with NameIdentity {
final String name;
Person(this.name);
}
实现接口
abstract interface class Tuner {
void tuneInstrument();
}
mixin Guitarist implements Tuner {
void playSong() {
tuneInstrument();
print('Strums guitar majestically.');
}
}
class PunkRocker with Guitarist {
@override
void tuneInstrument() {
print("Don't bother, being out of tune is punk rock.");
}
}
mixin里面的继承 on
class Musician {
musicianMethod() {
print('Playing music!');
}
}
mixin MusicalPerformer on Musician {
performerMethod() {
print('Performing music!');
super.musicianMethod();
}
}
class SingerDancer extends Musician with MusicalPerformer { }
main() {
SingerDancer().performerMethod();
}
定义mixin class 至少3.0支持
mixin class Musician {
}
class Novice with Musician { // Use Musician as a mixin
}
class Novice extends Musician { // Use Musician as a class
}
43枚举
用于表示固定数量的常量值
自动扩展 Enum 类。 这意味着它们不能被子类化、实现、混合、 或以其他方式显式实例化
声明枚举
enum Color { red, green, blue }
增强型枚举
enum Vehicle implements Comparable<Vehicle> {
car(tires: 4, passengers: 5, carbonPerKilometer: 400),
bus(tires: 6, passengers: 50, carbonPerKilometer: 800),
bicycle(tires: 2, passengers: 1, carbonPerKilometer: 0);
const Vehicle({
required this.tires,
required this.passengers,
required this.carbonPerKilometer,
});
final int tires;
final int passengers;
final int carbonPerKilometer;
int get carbonFootprint => (carbonPerKilometer / passengers).round();
bool get isTwoWheeled => this == Vehicle.bicycle;
@override
int compareTo(Vehicle other) => carbonFootprint - other.carbonFootprint;
}
使用枚举
final favoriteColor = Color.blue;//获取枚举
assert(Color.red.index == 0);//enum 声明中值的从零开始的位置。第一个值的索引为 0, 第二个值的索引为 1
List<Color> colors = Color.values;//获取所有枚举值的列表
Color.blue.name//访问枚举值的名称
44扩展方法
定义
extension <extension name>? on <type> { // 扩展名是可选的( 未命名的扩展仅可见在声明它们的库中)
(<member definition>)* // Can provide one or more <member definition>.
}
例子
extension NumberParsing on String {
int parseInt() {
return int.parse(this);
}
}
使用
print('42'.parseInt()); // Use an extension method.
dynamic d = '2';
print(d.parseInt()); // dynamic不能使用
var v = '2';
print(v.parseInt()); // 类型推断var可以使用
扩展冲突
方式1
import 'string_apis.dart';
import 'string_apis_2.dart' hide NumberParsing2;//隐藏一个
方式2
import 'string_apis.dart'; // Contains NumberParsing extension.
import 'string_apis_2.dart'; // Contains NumberParsing2 extension.
print(NumberParsing('42').parseInt());
print(NumberParsing2('42').parseInt());//显示调用
方式3
import 'string_apis.dart';
import 'string_apis_3.dart' as rad;//前缀导入
print(NumberParsing('42').parseInt());
print(rad.NumberParsing('42').parseInt());
泛型扩展
extension MyFancyList<T> on List<T> {
int get doubleLength => length * 2;
List<T> operator -() => reversed.toList();
List<List<T>> split(int at) => [sublist(0, at), sublist(at)];
}
45扩展类型
extension type E(int i) {
// Define set of operations.
}
46可调用对象
class WannabeFunction {
String call(String a, String b, String c) => '$a $b $c!';//需要实现此方法
}
var wf = WannabeFunction();
var out = wf('Hi', 'there,', 'gang');//想调用函数一样调用对象
void main() => print(out);
47类修饰符
除了abstract,都需要至少3.0版本
abstract:通常具有抽象方法
abstract class Vehicle {
void moveForward(int meters);
}
base:
base class Vehicle {
void moveForward(int meters) {}
}
import 'a.dart';
// Can be constructed.
Vehicle myVehicle = Vehicle();
// Can be extended.
base class Car extends Vehicle {
int passengers = 4;
}
// ERROR: Can't be implemented.
base class MockVehicle implements Vehicle {
@override
void moveForward() {}
}
interface:
interface class Vehicle {
void moveForward(int meters) {}
}
import 'a.dart';
// Can be constructed.
Vehicle myVehicle = Vehicle();
//ERROR: Can't be inherited.
class Car extends Vehicle {
int passengers = 4;
}
// Can be implemented.
class MockVehicle implements Vehicle {
@override
void moveForward() {}
}
abstract interface:
final:不允许继承和实现会完全阻止子类型化
final class Vehicle {
void moveForward(int meters) {}
}
import 'a.dart';
// Can be constructed.
Vehicle myVehicle = Vehicle();
//ERROR: Can't be inherited.
class Car extends Vehicle {
int passengers = 4;
}
// ERROR: Can't be implemented.
class MockVehicle implements Vehicle {
@override
void moveForward() {}
}
sealed:
sealed class Vehicle {}
class Car extends Vehicle {}
class Truck implements Vehicle {}
class Bicycle extends Vehicle {}
// ERROR: Can't be instantiated.
Vehicle myVehicle = Vehicle();
// Subclasses can be instantiated.
Vehicle myCar = Car();
String getVehicleSound(Vehicle vehicle) {
// ERROR: The switch is missing the Bicycle subtype or a default case.
return switch (vehicle) {
Car() => 'vroom',
Truck() => 'VROOOOMM',
};
}
组合修饰符:https://dart.cn/language/modifier-reference/
48Dart并发
所有 Dart 代码都在 isolate 中运行,从默认的 main isolate 开始
Dart 的运行时模型基于事件循环。 事件循环负责执行程序的代码 收集和处理事件
异步编程
Future
Future<String> _readFileAsync(String filename) {
final file = File(filename);
// .readAsString() returns a Future.
// .then() registers a callback to be executed when `readAsString` resolves.
return file.readAsString().then((contents) {
return contents.trim();
});
}
async-await
Future<String> _readFileAsync() async {
final file = File(filename);
final contents = await file.readAsString();
return contents.trim();
}
Stream
Stream<int> stream = Stream.periodic(const Duration(seconds: 1), (i) => i * i);
await-for 和 yield
Stream<int> sumStream(Stream<int> stream) async* {
var sum = 0;
await for (final value in stream) {
yield sum += value;
}
}
Isolate
只有 Dart Native 平台实现了 isolates。 Dart Web 平台没实现
使用Isolate
使用 Isolate.run() 在单独的线程上执行单个计算。(推荐使用)
int slowFib(int n) => n <= 1 ? 1 : slowFib(n - 1) + slowFib(n - 2);
// Compute without blocking current isolate.
void fib40() async {
/方法需要一个参数:一个回调,该回调将是 在新生成的 isolate 上运行
var result = await Isolate.run(() => slowFib(40));
print('Fib(40) = $result');
}
使用 Isolate.spawn() 创建一个 isolate 语句,该 isolate 将处理多个 消息,或后台 worker
web上的并发
web worker
49异步支持
处理Future的两种方式
使用async......await
使用Future.then()
处理Stream
使用 async......await for
await for (varOrType identifier in expression) {
// Executes each time the stream emits a value.
}
执行过程如下:expression
等待流发出值。
执行 for 循环的主体 并将变量设置为该 emitted 值。
重复 1 和 2,直到流关闭。
使用Stream 的api
处理Isolate
解析和解码超大型 JSON blob。
处理和压缩照片、音频和视频。
转换音频和视频文件。
对大型列表或 Within 执行复杂的搜索和筛选 文件系统。
执行 I/O,例如与数据库通信。
处理大量网络请求
如果你使用的是 Flutter,则可以使用 Flutter 的计算函数(https://api.flutter-io.cn/flutter/foundation/compute.html)而不是 Isolate.run()
使用
const String filename = 'with_keys.json';
void main() async {
// Read some data.
final jsonData = await Isolate.run(_readAndParseJson);//传入耗时函数名
// Use that data.
print('Number of JSON keys: ${jsonData.length}');
}
//定义耗时函数
Future<Map<String, dynamic>> _readAndParseJson() async {
final fileData = await File(filename).readAsString();
final jsonData = jsonDecode(fileData) as Map<String, dynamic>;
return jsonData;
}
长期Isolate
第一步:定义worker类,此类包含您需要的所有功能
生成一个隔离。
向该隔离地址发送消息。
让 isolate 解码一些 JSON。
将解码后的 JSON 发送回主隔离
class Worker {
Future<void> spawn() async {
// 生成一个新的isolate
}
void _handleResponsesFromIsolate(dynamic message) {
// TODO: Handle messages sent back from the worker isolate.
}
static void _startRemoteIsolate(SendPort port) {
// TODO: Define code that should be executed on the worker isolate.
}
Future<void> parseJson(String message) async {
//这个是能把数据返回给main isolate
}
}
第二步
Future<void> spawn() async {
final receivePort = ReceivePort();
receivePort.listen(_handleResponsesFromIsolate);//接收work isolate的消息
await Isolate.spawn(_startRemoteIsolate, receivePort.sendPort);//生成worker isolate
}
第三步
static void _startRemoteIsolate(SendPort port) {
final receivePort = ReceivePort();
port.send(receivePort.sendPort);
receivePort.listen((dynamic message) async {
if (message is String) {
final transformed = jsonDecode(message);
port.send(transformed);
}
});
}
第四步
void _handleResponsesFromIsolate(dynamic message) {
if (message is SendPort) {
_ sendPort = message;
isolateReady.complete();
} else if (message is Map<String, dynamic>) {
print(message);
}
}
第五步
Future<void> parseJson(String message) async {
await _isolateReady.future;
_ sendPort.send(message);
}
增强型示例 https://dart.cn/language/isolates/
50空安全
在 Dart 2.12 到 2.19 中,你需要手动启用空安全。 Dart 2.12 之前的 SDK 版本不提供空安全
建议使用 Dart SDK 2.12 到 2.19 版本中包含的 dart migrate 工具。
51操作符..可以返回调用者本身
52Dart的核心库
dart:core 内置类型、集合和其他核心功能。 这个库会自动导入到每个 Dart 程序中
dart: async 支持异步编程,包括 Future 和 Stream 等类。
dart: math 数学常数和函数,以及随机数生成器。
dart: convert 用于在不同数据表示之间进行转换的编码器和解码器, 包括 JSON 和 UTF-8。
dart: io I/O 用于可以使用 Dart VM 的程序, 包括 Flutter 应用、服务器和命令行脚本。
dart:html DOM 和其他 API。 我们现在建议使用 package:web
多平台库(适用于所有dart平台)
dart:core
dart:async, package:async
dart:collection, package:collection
dart:convert, package:convert
dart:developer
dart:math
dart:typed_data, package:typed_data
原生平台库( Dart 原生平台上工作的 Dart 核心库(AOT 和 JIT 编译的代码))
dart:ffi, package:ffi
dart:io、package:io
dart:isolate
dart:mirrors
Web 平台库(编译为 JavaScript 的代码)
package:web
dart:js_interop
dart:js_interop_unsafe
dart:html (legacy)
dart:indexed_db (legacy)
dart:js, dart:js_util, package:js (legacy)
dart:svg (legacy)
dart:web_audio (legacy)
dart:web_gl (旧版)
53.dart:core核心库
var loudTeas = teas.map((tea) => tea.toUpperCase()).toList();//集合的map()方法是懒加载的,必须要请求里面的数据获取调用toList或toSet它才会执行
var decaffeinatedTeas = teas.where((tea) => isDecaffeinated(tea));//集合的where方法是找出所有符合条件的条目
assert(teas.any(isDecaffeinated));//集合的any方法检查是否有一项符合条件
assert(!teas.every(isDecaffeinated));//集合的every是检查是否所有条目都符合条件
//解析指定日期的时间
DateTime(2000, 1, 2);
DateTime.utc(2000);
DateTime.parse('2000-01-01T00:00:00Z');
实现Comparable接口可以对比两个对象
class Line implements Comparable<Line> {
final int length;
const Line(this.length);
@override
int compareTo(Line other) => length - other.length;
}
如果修改了类的hashCode值还必须修改operator方法
自定义的Exception是实现Exception接口
class FooException implements Exception {
final String? msg;
const FooException([this.msg]);
@override
String toString() => msg ?? 'FooException';
}
要保证一个对象不会太早被垃圾回收期回收可以将类实现 Finalizable
54.dart:async核心库
逐步运行多个异步
Future result = costlyQuery(url);
result
.then((value) => expensiveWork(value))
.then((_) => lengthyComputation())
.then((_) => print('Done!'))
.catchError((exception) {
/* Handle exception... */
});
有时候依赖于多个异步执行完后再进行下一步,可以用Future.wait
await Future.wait([
deleteLotsOfFiles(),
copyLotsOfFiles(),
checksumLotsOfOtherFiles(),
]);
Future.delay可以不加await
Future的then里面如果有异常不会走catchError方法
Future的catchError的第二个参数test指示了是否处理这个异常,这对区分不同类型的异常做不同处理很有作用
Future.wait可以捕获异常的版本,当不需要返回值时可使用
try {
// Wait for each future in a list, returns a list of futures:
var results = await [delete(), copy(), errorResult()].wait;
} on ParallelWaitError<List<bool?>, List<AsyncError?>> catch (e) {
print(e.values[0]); // Prints successful future
print(e.values[1]); // Prints successful future
print(e.values[2]); // Prints null when the result is an error
print(e.errors[0]); // Prints null when the result is successful
print(e.errors[1]); // Prints null when the result is successful
print(e.errors[2]); // Prints error
}
Future.wait可以处理返回值的版本(返回值是单个的)
try {
// Wait for each future in a record, returns a record of futures:
(int, String, bool) result = await (delete(), copy(), errorResult()).wait;
} on ParallelWaitError<(int?, String?, bool?),
(AsyncError?, AsyncError?, AsyncError?)> catch (e) {
}
// Do something with the results:
var deleteInt = result.$1;
var copyString = result.$2;
var errorBool = result.$3;
Stream的异步代码版本
FileSystemEntity.isDirectory(searchPath).then((isDir) {
if (isDir) {
final startingDir = Directory(searchPath);
startingDir.list().listen((entity) {
if (entity is File) {
searchFile(entity, searchTerms);
}
});
} else {
searchFile(File(searchPath), searchTerms);
}
});
Stream的同步代码版本:如果需要等待所有异步的事件处理完毕使用这个
if (await FileSystemEntity.isDirectory(searchPath)) {
final startingDir = Directory(searchPath);
await for (final entity in startingDir.list()) {
if (entity is File) {
searchFile(entity, searchTerms);
}
}
} else {
searchFile(File(searchPath), searchTerms);
}
Stream s;
//获取单个事件
s.first
s.last
s.single
//条件性的获取单个事件
firstWhere(), lastWhere(), or singleWhere().
//获取事件子集
skip(), skipWhile(), take(), takeWhile(), and where().
使用transform方法来转换流
var lines = inputStream.transform(utf8.decoder).transform(const LineSplitter());
处理Stream的异常
同步异常处理
Future<void> readFileAwaitFor() async {
var config = File('config.txt');
Stream<List<int>> inputStream = config.openRead();
var lines =
inputStream.transform(utf8.decoder).transform(const LineSplitter());
try {
await for (final line in lines) {
print('Got ${line.length} characters from stream');
}
print('file is now closed');
} catch (e) {
print(e);
}
}
异步异常处理
var config = File('config.txt');
Stream<List<int>> inputStream = config.openRead();
inputStream.transform(utf8.decoder).transform(const LineSplitter()).listen(
(String line) {
print('Got ${line.length} characters from stream');
}, onDone: () {
print('file is now closed');
}, onError: (e) {
print(e);
});
55.Async
Future.whenComplete 就像是finally
Future.whenComplete 返回的Future跟上一级的返回时相同的,要么then的返回,要么catchError的返回
Future.sync 允许当一个异步返回的函数中有同步和异步代码时,同步的代码出现异常也能被外层的catchError捕获
处理Stream有两种方式:listen()方法和 await for关键字
Stream有两种类型:Single-Subscription和Broadcast
通过调用Stream的asBroadcastStream方法让它可以产生多个订阅者
Stream的不一定需要await给他一次性生成
在使用await for去使用流之前给流一个错误处理程序
Stream<S> mapLogErrors<S, T>(
Stream<T> stream,
S Function(T event) convert,
) async* {
var streamWithoutErrors = stream.handleError((e) => log(e));
await for (final event in streamWithoutErrors) {
yield convert(event);
}
}
创建流的方式
转换存在的流
使用async*函数
使用StreamController:弥补使用async*无法处理多个数据源的不足
如果流没有订阅者,他会缓存事件,如果一直没有订阅者,可能导致内存泄漏
静态转换
var counterStream = Stream<int>.periodic(const Duration(seconds: 1), (x) => x).take(15);//周期性生成
使用StreamController的正确方式
//StreamController的四个监听参数决定了其是否使用add方法
Stream<int> timedCounter(Duration interval, [int? maxCount]) {
late StreamController<int> controller;
Timer? timer;
int counter = 0;
void tick(_) {
counter++;
controller.add(counter); // Ask stream to send counter values as event.
if (counter == maxCount) {
timer?.cancel();
controller.close(); // Ask stream to shut down and tell listeners.
}
}
void startTimer() {
timer = Timer.periodic(interval, tick);
}
void stopTimer() {
timer?.cancel();
timer = null;
}
controller = StreamController<int>(
onListen: startTimer,//有流的订阅者调用(他会在返回订阅者之前调用)
onPause: stopTimer,//流的订阅者暂停
onResume: startTimer,//流的订阅者继续监听
onCancel: stopTimer);//订阅者取消监听
return controller.stream;
}
56.迭代集合
for-in
firstWhere :第一个符合条件的,如果没有会抛异常,所以最好写orElse参数
singleWhere :只需要一个元素满足,如果有多个或没有满足也会抛异常,这个最好用于少数据量的条件
every :检查所有元素是否满足条件
any :如果有一个元素满足条件就是true
where :找到符合条件的所有元素
takeWhile :找到符合条件前的所有元素
skipWhile :找到符合条件后的所有元素
map : 将集合里面的元素转换成另外一个对象,这个方法是懒加载的,只有在使用的时候才会执行
57.yield*可以代表流的完成
Stream<T> optionalMap<T>(Stream<T> source, [T Function(T)? convert]) async* {
if (convert == null) {
yield* source; //当源流关闭时,yield* 完成
} else {
await for (var event in source) {
yield convert(event);
}
}
}
58.Timer里面的执行函数是异步的
59.无序集合
HashMap HashSet
planets.update(4, (v) => 'Saturn');//有条件的更新值
planets.putIfAbsent(4, () => 'Another Saturn');//更新值,如何没有此值就添加
60.有序集合
LinkedHashMap LinkedHashSet
61.排序集合
SplayTreeMap SplayTreeSet
62.元素不可变集合
UnmodifiableListView UnmodifiableMapView UnmodifiableSetView
final numbers = <int>[10, 20, 30];
final unmodifiableListView = UnmodifiableListView(numbers);
numbers.addAll([40, 50]);
print(unmodifiableListView); // [10, 20, 30, 40, 50]
unmodifiableListView.remove(20); //报错
63.ListQueue 基于列表的队列,可以在列表的首位进行操作,适应于任务调度的场景
64.数据的编码和解码
- json
var encoded = json.encode([1, 2, { "a": null }]);
var decoded = json.decode('["foo", { "bar": 499 }]');
//方式2
const JsonDecoder decoder = JsonDecoder();
const String jsonString = '''
{
"data": [{"text": "foo", "value": 1 },
{"text": "bar", "value": 2 }],
"text": "Dart"
}
//将原本不受支持的对象编码成json
class CustomClass {
final String text;
final int value;
CustomClass({required this.text, required this.value});
CustomClass.fromJson(Map<String, dynamic> json)
: text = json['text'],
value = json['value'];
static Map<String, dynamic> toJson(CustomClass value) =>
{'text': value.text, 'value': value.value};
}
void main() {
final CustomClass cc = CustomClass(text: 'Dart', value: 123);
final jsonText = jsonEncode({'cc': cc},
toEncodable: (Object? value) => value is CustomClass //使用toEncodable方法
? CustomClass.toJson(value)
: throw UnsupportedError('Cannot convert to JSON: $value'));
print(jsonText); // {"cc":{"text":"Dart","value":123}}
}
''';
final Map<String, dynamic> object = decoder.convert(jsonString);
final item = object['data'][0];
print(item['text']); // foo
print(item['value']); // 1
print(object['text']); // Dart
//格式化编码
const JsonEncoder encoder = JsonEncoder.withIndent(' ');
const data = {'text': 'foo', 'value': '2'};
final String jsonString = encoder.convert(data);
print(jsonString);
// {
// "text": "foo",
// "value": "2"
// }
- utf8
var encoded = utf8.encode('Îñţérñåţîöñåļîžåţîờñ');
var decoded = utf8.decode([
195, 142, 195, 177, 197, 163, 195, 169, 114, 195, 177, 195, 165, 197,
163, 195, 174, 195, 182, 195, 177, 195, 165, 196, 188, 195, 174, 197,
190, 195, 165, 197, 163, 195, 174, 225, 187, 157, 195, 177]);
- ASCII
var encoded = ascii.encode('This is ASCII!');
var decoded = ascii.decode([0x54, 0x68, 0x69, 0x73, 0x20, 0x69, 0x73,
0x20, 0x41, 0x53, 0x43, 0x49, 0x49, 0x21]);
//decode将字节转换成ascii,数字大小从0..127,如果超过127,使用Unicode码 U+FFFD ('�').代替
const asciiDecoder = AsciiDecoder(allowInvalid: true);//allowInvalid 默认false
final asciiValues = [68, 97, 114, 116, 20, 0xFF];
final result = asciiDecoder.convert(asciiValues);
print(result); // Dart �
print(result.codeUnits.last.toRadixString(16)); // fffd
- Latin-1. ISO Latin-1 (aka ISO-8859-1)
var encoded = latin1.encode('blåbærgrød');
var decoded = latin1.decode([0x62, 0x6c, 0xe5, 0x62, 0xe6,
0x72, 0x67, 0x72, 0xf8, 0x64]);
- Base64
var encoded = base64.encode([0x62, 0x6c, 0xc3, 0xa5, 0x62, 0xc3, 0xa6,
0x72, 0x67, 0x72, 0xc3, 0xb8, 0x64]);
var decoded = base64.decode('YmzDpWLDpnJncsO4ZAo=');
//解码:如果编码字符次的字符不合法,会引发 FormatException 异常
final base64Decoder = base64.decoder;
const base64Bytes = 'RGFydCBpcyBvcGVuIHNvdXJjZQ==';
final decodedBytes = base64Decoder.convert(base64Bytes);// decodedBytes: [68, 97, 114, 116, 32, 105, 115, 32, 111, 112, 101, 110, 32, 115, 111, 117, 114, 99, 101]
print(utf8.decode(decodedBytes)); // Dart is open source
//编码
final base64Encoder = base64.encoder;
const sample = 'Dart is open source';
final encodedSample = base64Encoder.convert(sample.codeUnits);
print(encodedSample); // RGFydCBpcyBvcGVuIHNvdXJjZQ==
- Stream.transform Converters 直接对流进行转换
const showLineNumbers = true;
var lineNumber = 1;
var stream = File('quotes.txt').openRead();
stream.transform(utf8.decoder)//将流解码成utf8
.transform(const LineSplitter())//在换行符边界上分割数据。
.forEach((line) {
if (showLineNumbers) {
stdout.write('${lineNumber++} ');
}
stdout.writeln(line);
});
- 符号和Html互转
const htmlEscapeMode = HtmlEscapeMode(
name: 'custom',
escapeLtGt: true,
escapeQuot: false,
escapeApos: false,
escapeSlash: false,
);
const HtmlEscape htmlEscape = HtmlEscape(htmlEscapeMode);
String unescaped = 'Text & subject';
String escaped = htmlEscape.convert(unescaped);
print(escaped); // Text & subject
unescaped = '10 > 1 and 1 < 10';
escaped = htmlEscape.convert(unescaped);
print(escaped); // 10 > 1 and 1 < 10
unescaped = "Single-quoted: 'text'";
escaped = htmlEscape.convert(unescaped);
print(escaped); // Single-quoted: 'text'
unescaped = 'Double-quoted: "text"';
escaped = htmlEscape.convert(unescaped);
print(escaped); // Double-quoted: "text"
unescaped = 'Path: /system/';
escaped = htmlEscape.convert(unescaped);
print(escaped); // Path: /system/
- 换行符专用转换器
const splitter = LineSplitter();
const sampleText =
'Dart is: \r an object-oriented \n class-based \n garbage-collected '
'\r\n language with C-style syntax \r\n';
final sampleTextLines = splitter.convert(sampleText);
for (var i = 0; i < sampleTextLines.length; i++) {
print('$i: ${sampleTextLines[i]}');
}
// 0: Dart is:
// 1: an object-oriented
// 2: class-based
// 3: garbage-collected
// 4: language with C-style syntax
65.超大数字 BitInt
var bigInteger = BigInt.from(-1); // -1
var value = BigInt.parse('0x1ffffffffffffffff'); // 36893488147419103231
print(bigValue.isValidInt); // true
print(bigValue.toInt()); // 1000
66.关于DateTime的时间换算
- 时区换算都是以utc时间为基准去算的,像美国西x去就是减去学xx小时,中国就是东x去就是加上xx小时
- 时间戳的换算都是 epoch 开始时间(1970-01-01 utc)去算的
final now = DateTime.now();//当地时间
final dDayLocal = DateTime(1944, 6, 6);//当地时间
final dDay = DateTime.utc(1944, 6, 6);// utc
final moonLanding = DateTime.parse('1969-07-20 20:18:04Z'); // utc
final localDay = dDay.toLocal(); // utc转当地时间
final utcFromLocal = localDay.toUtc(); // 当地时间转utc
print(localDay.timeZoneName); // 当地时间名。eg:PST
print(localDay.timeZoneOffset); // 计算当地时间和utc时间相差的时间
print(dDay.isAtSameMomentAs(localDay)); // 是否同一时间,会自动转换utc和当地时间
67.函数类 Function
String numberToString(int n) => "$n"; // 普遍
String Function(int n) fun = numberToString; // 有返回值,有参数
String Function() fun2 = (){ return "";}; // 有返回值,无参数
Function fun3 = (){}; //无返回值
68.Future的异常正确处理
int i = await a().then((value) {
//正常获取到了值
return value;//此处的返回值必须要加,如果不加返回值,那么不管onError是否有返回,在有onError回调的情况下走onError,
//否则有catchError的i情况下走cathcError
}, onError: (e, s) {
print("onError");
bool noCatchError = false;//决定了是否走catchError逻辑
if(noCatchError){
return 1;
}
}).catchError((e,s){
print("catchError");
bool handle = false;
if(handle){
return 2;
}
return 0;//必须要,不然可能报错
});
print(i);
69.Future的静态调用
- Future.timeout(duration,callback) 可以处理等待Future返回的超时时间
- Future.any([slowInt(), delayedString(), fastInt()]) 将任何一个返回作为结果,其他丢弃
- Future.doWhile() 知道返回true,否则将一直循环执行
Future.doWhile(() async {
value++;
await Future.delayed(const Duration(seconds: 1));
if (value == 3) {
print('Finished with $value');
return false;
}
print(value);
return true;
});
- Future.forEach() 迭代执行Future列表,并不会等待某个执行完了再执行下一个,中间有失败了的会直接停止
- Future.wait() //执行列表,如果结果都是成功的则以列表形式返回数据,如果某个失败了,则看第二个参数如果为true,
//会停止执行后面的,如果为false,所有的都会执行,值得一提的是所有的Future都是同步执行的,并不是一个一个等待执行
70.集合实现的 Iterable 增删改查的所有公共方法
- 构造相关
List<int>.empty();
List<int>.generate(4,(i){
return 1;
});
- 属性相关
//获取第一个元素
list.first;
set.firstOrNull;
//单列集合转下标元素对Pairs
var arr = list.indexed;
var indexed = set.indexed;
//判空
list.isEmpty;
map.isEmpty;
set.isEmpty;
//带游标的迭代
list.iterator;
set.iterator;
//最后一个元素
list.last;
set.lastOrNull;
//长度
list.length;
map.length;
set.length;
//去掉null元素
list.nonNulls;
set.nonNulls;
//判断和获取元素合并,适应于判断只有一个元素
list.single;
set.singleOrNull;
- 方法函数相关
//只要有一个元素满足条件就返回true,否则false
list.any();
set.any();
//将里面的类型进行强转
list.cast();
map.cast();
set.cast();
//是否包含某个元素
list.contains();
set.contains();
//获取指定下标的元素
list.elementAt(1);
set.elementAtOrNull(5);
//集合中的所有元素是否满足某个条件
list.every();
set.every();
//对集合中的每个元素进行扩展,,每个元素都可以扩展成一个集合
list.expand();
set.expand();
//集合中第一个满足条件的元素
list.firstWhere();
set.firstWhere();
//提供一个初始值,每次通过将上一个元素和当前元素进行组合,并逐渐减少元素的值至单个
list.fold();
set.fold();
//将集合元素添加在调用方集合的后面,懒加载方式,注意:合并后的数据在新的集合里面
list.followedBy();
set.followedBy();
//对每个元素进行自定义action操作,也可作为元素的迭代
list.forEach();
map.forEach();
set.forEach();
//将集合拼接成字符串,中间可以用指定的字符串进行拼接,默认空串
list.join();
set.join();
//最后一个满足条件的元素
list.lastWhere();
set.lastWhere();
//将元素转换成的新的元素
list.map();
map.map();
set.map();
//通过将上一个元素和当前元素进行组合,并逐渐减少元素的值至单个,类似于fold方法,值得注意的是调用此方法的集合不能为空
list.reduce();
set.reduce();
//单个元素满足条件true,多个元素满足引发异常,没有元素满足条件要么引发异常,要么orElse方法
list.singleWhere();
set.singleWhere();
//生成忽略前n个元素的新的集合
list.skip();
set.skip();
//按条件生成忽略前n个元素的直至条件为false的新的集合
list.skipWhile();
set.skipWhile();
//拿取集合中指定个数元素生成新的集合
list.take();
set.take();
//按条件拿取前面的元素产生新的集合直至条件为false
list.takeWhile();
set.takeWhile();
//集合互转
list.toSet();
set.toList();
//按条件为true生成新的集合
list.where();
set.where();
//在集合中拿去指定类型的元素生成新的集合
list.whereType();
set.whereType();
- 静态方法
//将集合的元素转换成元素子类型的集合
List.castFrom();
Map.castFrom();
Set.castFrom();
Iterable.castFrom(source)
//将集合转成字符串,中间用,分割,两边可自定义
Iterable.iterableToFullString();
Iterable.iterableToShortString();//字符串长度有限,后面可能使用...结尾
71.Iterator 相当于一个游标指针有 moveNext方法
72.List相关方法
- 构造方法
//创建空的列表
List.empty();
//创建指定长度并使用同一个值初始化元素的列表
final shared = List.filled(3, []);
shared[1].add(499);//三个元素指向了同一个数组对象,所以每个元素都被影响了,其他的数据类型好像不会相互影响
print(shared);//[[499], [499], [499]]
//从已有的集合生成一个新的集合(两个集合的类型不必一致)
List<int>.from(numbers);
//创建指定长度的自定义元素值的列表
List.generate();
//从已有的集合生成一个新的集合(两个集合的类型必须一致)
List.of();
//创建长度和对象均不可变的集合
List.unmodifiable();
- 属性
//集合反转
final ll = list.reversed;
- 方法
//添加元素
list.add();
list.addAll();
//将范围内的元素填充为其他值
list.fillRange();
//获取指定范围的元素
list.getRange();
//获取指定元素的下标
list.indexOf(element);
list.indexWhere(test);
//在指定下标处插入元素
list.insert();
list.insertAll();
//获取最后一个元素或下标相关
list.lastIndexOf();
list.lastIndexWhere();
list.lastWhere();
//移除元素和下标相关
list.remove(2);
list.removeAt();
list.removeLast();
list.removeRange();
list.removeWhere();
//替换指定范围的元素为新的值
list.replaceRange();
//保留指定条件的元素-直接操作数据源
list.retainWhere();
//从指定下标起替换元素的值为新集合的元素
list.setAll();
list.setRange();
//打乱元素的顺序
list.shuffle();
//将元素排序
list.sort();
//获取子集合
list.sublist();
- 操作符相关,使用 + 可以拼接集合
- 静态方法
//将一个集合中的一部分数据复制到另一个集合中去
List.copyRange();
//将一个Iterable的元素写入到另一个集合当中去
List.writeIterable();
73.Map相关方法
- 构造方法
//从另一个Map复制过来生成一个Map,from方法适合类型强转
Map.from();
Map.of();
Map.fromEntries();
//将两个单例集合合并成一个双列集合
Map.fromIterables();
//在单列集合的基础上生成双列集合
Map.fromIterable()
//使用地址来对比key是否相同
Map.identity();
//长度不可变的Map
Map.unmodifiable();
- 属性
//将Map集合的单个key和value转换成一个对象
map.entries;
//获取所有的key
map.keys;
//获取所有的value
map.values;
- 方法
//添加另一个集合中的所有值
map.addAll();
map.addEntries();
//转换key和value的类型
map.cast();
//清空集合
map.clear();
//是否包含指定key或者value
map.containsKey();
map.containsValue();
//遍历map
map.forEach();
74.正则 Match
- 示例:匹配所有单词
final regExp = RegExp(r'(\w+)');
const string = 'Hello, world! This is a test 123.';
final matches = regExp.allMatches(string);
for (final m in matches) {
String match = m[0]!;
print(match);
}
75.关于 Null 类的一些操作
obj! 如果o为null会报错
obj ?? obj2 如果obj为null则使用obj2
obj ??= obj2 如果obj为null则赋值,否则不赋值
obj?.toString() 如果obj为null,则不调用toString否则调用
[...? obj] 如果obj不为null,就把他添加在集合当中去
76.num类(其代表了 int 和 double)
- 属性
n.isFinite; //是否有限的,唯一的非有限数是 NaN 值、正无穷大和负无穷大。所有整数都是有限的
n.isInfinite; //是否无限的
n.isNaN; //连 double.nan 此数字是否为 Not-a-Number 值,所有数字都只满足 isInfinite、isFinite 和 isNaN 中的一个
n.isNegative; //是否为负数
n.sign; //获取数字的符号 1 正数 -1 负数 0 就是0
- 方法函数
a.abs(); //取绝对值
a.ceil(); //不小于此值的最小整数
a.ceilToDouble(); //不小于此值的最小整数再转浮点数
a.clamp(); //取指定区间值
a.compareTo(); //是否前者比较大,1 -1 0
a.floor(); //不大于此值的最小整数
a.floorToDouble(); //不大于此值的最小整数再转浮点数
n.remainder(); //求余数
n.round(); //最靠近他的整数,往x轴两边走
n.roundToDouble(); //最靠近他的整数再转成小数,往x轴两边走
n.toDouble(); //转成小数
n.toInt(); //转成整数
n.toStringAsExponential();
n.toStringAsFixed(); //留几位小数
n.toStringAsPrecision();
n.truncate(); //舍弃小数位
n.truncateToDouble();
- 静态方法
num.tryParse(); //将非数字转成数字,转不了返回null
77.Object类
- 构造
Object();
- 静态方法
//计算多个Object对象的hash值
Object.hash();
Object.hashAll();
Object.hashAllUnordered();
78.Pattern类:用于字符串的搜索功能的接口 RegExp String 都实现了他
79.pragma类,用于注解
80.Record类
(int, String, {bool isValid}) triple = (1, "one", isValid: true);
81.RegExp类
- 构造
RegExp(r'(\w+)');
- 属性
re.isCaseSensitive; //是否忽略大小写
re.isDotAll; //此正则表达式中的 “.” 是否与行终止符匹配
re.isMultiLine; //此正则表达式是否匹配多行。如果 regexp 匹配多行,则 “^” 和 “$” 字符匹配行的开头和结尾。否则,字符将匹配输入的开头和结尾。
re.isUnicode; //正则表达式是否使用 Unicode 模式
re.pattern; //正则表达式原串
- 方法函数
exp.allMatches(); //匹配所有
exp.firstMatch(); //第一个匹配到的
exp.hasMatch(); //是否有匹配到的
exp.matchAsPrefix(); //是否从给定的地方正好匹配到,默认0位置
exp.stringMatch(); //匹配第一个字符串
- 静态方法
RegExp.escape(); //创建与字符串匹配的正则字符串
82.RegExpMatch类
- 属性
regExpMatch.end; //字符串中匹配项最后一个字符之后的索引
regExpMatch.groupCount; //搞不懂
regExpMatch.input; //匹配源
regExpMatch.pattern; //匹配的正则
regExpMatch.start; //第一个被匹配到的地方
- 方法函数
regExpMatch.group(); //等于 regExpMatch[i] , i 为 0 时表示整个匹配项
regExpMatch.groups();
83.RuneIterator类
- 构造
RuneIterator();
RuneIterator.at();
- 属性
ri.current; //当前索引,默认-1
ri.currentAsString; //当前索引下的字符
ri.currentSize; //code units
ri.rawIndex;
ri.string; //原串
- 方法函数
ri.moveNext(); //移动到下一个,更新current
ri.movePrevious(); //移动到上一个,更新current
ri.reset(); //重置
84.Runes类 用于处理字符串的unicode值,可迭代的
85.Set类 :无序,不重复
- 构造
Set();
Set.from(); //用于将类型向下转换
Set.identity(); //创建空集
Set.of(elements); //从元素(已有的迭代器)创建Set
Set.unmodifiable(); //创建不可变的Set
- 属性
set.first;
set.firstOrNull;
set.indexed; //生成索引和元素对
set.isEmpty;
set.isNotEmpty;
set.iterator;
set.last;
set.lastOrNull;
set.length;
set.nonNulls;
set.single; //集合是否只有一个元素,并且成立时返回他
set.singleOrNull; //集合是否只有一个元素,并且成立时返回他
set.wait; //当集合里面的元素全是Future时可调用
- 方法函数
set.add();
set.addAll();
set.any(); //是否有一个满足条件
set.asNameMap(); //Set里面的值类型为枚举类型
set.byName(); //Set里面的值类型为枚举类型
set.cast(); //转换集合中的类型
set.clear();
set.contains();
set.containsAll();
set.difference();
set.elementAt();
set.elementAtOrNull();
set.every();
set.expand();
set.firstWhere();
set.fold();
set.followedBy();
set.forEach();
set.join();
set.lastWhere();
set.lookup();
set.remove();
set.removeAll();
set.removeWhere();
set.retainAll();
set.retainWhere();
set.map();
set.reduce();
set.singleWhere();
set.skip();
set.skipWhile();
set.take();
set.takeWhile();
set.toList();
set.toSet();
set.union(); //去重合并
set.where();
set.whereType();
- 静态方法
Set.castFrom();
86.Sink类 :存储数据的容器 ;实现: ChunkedConversionSink EventSink
- 方法
sink.add();
sink.close();
87.StackTrace类
- 构造
StackTrace.fromString();
- 静态属性
StackTrace.current; //当前的调用堆栈信息
88.Stopwatch类: 一个秒表,用于在运行时测量时间
- 构造
Stopwatch();
- 属性
stopwatch.elapsed; //计数器转换为时间 0:00:00.000000
stopwatch.elapsedMicroseconds;
stopwatch.elapsedMilliseconds;
stopwatch.elapsedTicks;
stopwatch.frequency;
stopwatch.isRunning;
- 方法函数
stopwatch.reset(); //归0
stopwatch.start();
stopwatch.stop();
89.Stream类
89-1.Complete类:生成 Future 对象并在以后使用 value 或 error 完成它们的方法
适用于有异步但是无法使用 await 的情况, 基于回调的方式转换成基于Future的方式
class AsyncOperation {
final Completer _completer = new Completer();
Future<T> doOperation() {
_startOperation();
return _completer.future; // Send future object back to client.
}
// Something calls this when the value is ready.
void _finishOperation(T result) {
_completer.complete(result);
}
// If something goes wrong, call this.
void _errorHappened(error) {
_completer.completeError(error);
}
}
- 构造
Completer();
Completer.sync(); //如果使用此方法的话,在调用complete.complete()后还有调用方法的话则会一直等待complete.complete()方法走完才执行
- 属性
completer.future;
completer.isCompleted;
- 方法函数
completer.complete();
completer.completeError();
89-2.EventSink类:使用子类 StreamSink
89-3.Future类:异步操作的结果
- 构造
Future(); //方法里面的函数是Timer.run异步调用计算的结果
Future.delayed();
Future.error();
Future.microtask();
Future.sync();
Future.value();
- 方法函数
future.asStream();
future.catchError(); //第二个参数决定了是否处理此异常,false 表示不处理此异常,默认true
future.ignore(); //如果只管调用不管结果和异常则调用此方法,很好用,因为他不会抛出异常
future.onError();
future.then();
future.timeout(); //添加future返回的超时时间
future.whenComplete(); //添加future返回的超时时间
- 静态方法
Future.any(); //只要有一个完成,其他的都会被丢弃
Future.doWhile(); //重复执行一个异步或同步,直到返回false
Future.forEach(); //确保顺序执行同步执行Future
Future.wait(); //同时并行执行Future,第二个参数决定出现第一个异常是否影响其他Future执行,第二个参数是打印成功的值
89-4.FutureOr类:一般都是直接使用Future类
89-5.MultiStreamController类:由 Stream.multi 提供的增强型流控制器;其作用类似于普通的异步控制器,但也允许同步添加事件
- 继承自StreamController,但是增加了方法
multiController.addSync();
multiController.addErrorSync();
multiController.closeSync();
89-6.Stream类
89-7.StreamConsumer类:接受多个完整流的 “sink” 的抽象接口
- 方法
streamConsumer.addStream();
streamConsumer.close();
89-8.StreamController类
final streamController = StreamController(
onPause: () => print('Paused'),
onResume: () => print('Resumed'),
onCancel: () => print('Cancelled'),
onListen: () => print('Listens'),
);
streamController.stream.listen(
(event) => print('Event: $event'),
onDone: () => print('Done'),
onError: (error) => print(error),
);
var hasListener = streamController.hasListener; // true
streamController.add(999);
final stream = Stream<int>.periodic(
const Duration(seconds: 1), (count) => count * count).take(4);
await streamController.addStream(stream);
streamController.addError(Exception('Issue 101'));
await streamController.addStream(Stream.error(Exception('Issue 404')));
var isClosed = streamController.isClosed; // false
streamController.close();
isClosed = streamController.isClosed; // true
- 构造
StreamController(); //listen 之前可以缓存事件 add 事件
StreamController.broadcast(); //不会缓存 add 事件,listen 之前的事件将丢失
- 属性
sc.done; //发送完成事件,所有侦听器停止监听
sc.hasListener;
sc.isClosed;
sc.isPaused;
sc.onCancel;
sc.onListen;
sc.onPause;
sc.onResume;
sc.sink;
sc.stream;
- 方法函数
sc.add();
sc.addError();
sc.addStream();
sc.close();
89-9.StreamIterator 类:逐个消费流事件 的工具类。允许你手动控制从 Stream 中读取事件的过程
- 构造
StreamIterator();
- 属性
si.current;
- 方法函数
si.cancel();
si.moveNext();
89-10.StreamSink 类:用它的实现者就好了 IOSink StreamController WebSocket
89-10.StreamSubscription 类
final stream = Stream.periodic(const Duration(seconds: 1), (i) => i * i)
.take(10);
final subscription = stream.listen(print); // A StreamSubscription<int>.\
subscription.pause();
print(subscription.isPaused); // true
subscription.resume();
print(subscription.isPaused); // false
subscription.cancel();
- 属性
ssb.isPaused;
- 方法函数
ssb.asFuture(); //返回处理 onDone 和 onError 回调的 future
ssb.cancel();
ssb.onData();
ssb.onDone();
ssb.pause();
ssb.resume();
89-11.StreamTransformer 类:转换流
/// Starts listening to [input] and duplicates all non-error events.
StreamSubscription<int> _onListen(Stream<int> input, bool cancelOnError) {
// Create the result controller.
// Using `sync` is correct here, since only async events are forwarded.
var controller = StreamController<int>(sync: true);
controller.onListen = () {
var subscription = input.listen((data) {
// Duplicate the data.
controller.add(data);
controller.add(data);
},
onError: controller.addError,
onDone: controller.close,
cancelOnError: cancelOnError);
// Controller forwards pause, resume and cancel events.
controller
..onPause = subscription.pause
..onResume = subscription.resume
..onCancel = subscription.cancel;
};
// Return a new [StreamSubscription] by listening to the controller's
// stream.
return controller.stream.listen(null);
}
// Instantiate a transformer:
var duplicator = const StreamTransformer<int, int>(_onListen);
// Use as follows:
intStream.transform(duplicator);
- 构造
StreamTransformer();
StreamTransformer<List<int>, String>.fromBind();
StreamTransformer.fromHandlers();
- 方法函数
stf.bind();
stf.cast();
- 静态方法
StreamTransformer.castFrom();
89-12.StreamTransformerBase 类
89-13.StreamView 类:提供一个只读的 Stream 视图,隐藏底层 Stream 的实现
89-14.SynchronousStreamController 类:同步事件派发,当调用 add、addError 或 close 时,事件会立即同步派发给监听器
89-15.Timer 类:一个倒数计时器,可以配置为触发一次或重复触发,当定时器达到 0 时,定时器调用指定的回调函数
- 构造
Timer(); //执行一次
Timer.periodic(); //回调会以持续时间间隔重复调用,直到使用 cancel 函数取消
- 属性
timer.isActive; //非周期性的如果未执行未取消则为 true ,周期性的未取消则为 true
timer.tick; //事件调用的次数,从0开始计算,每调用一次递增
- 方法函数
timer.cancel(); //取消定时器
- 静态方法
Timer.run(() { }); //尽快异步运行给定的回调。
89-16.Zone 类
runZoned(() => null); //运行环境隔离
89-17.ZoneDelegate 类
89-18.ZoneSpecification 类
89-19.函数
- runZoned
var secret = "arglebargle"; // Or a random generated string.
var result = runZoned(
() async {
await Future.delayed(Duration(seconds: 5), () {
print("${Zone.current[#_secret]} glop glyf");
});
},
zoneValues: {#_secret: secret},
zoneSpecification:
ZoneSpecification(print: (Zone self, parent, zone, String value) {
if (value.contains(Zone.current[#_secret] as String)) {
value = "--censored--";
}
parent.print(zone, value);
}));
secret = ""; // Erase the evidence.
await result; // Wait for asynchronous computation to complete.
-
runZonedGuarded
-
scheduleMicrotask
//只要 scheduleMicrotask 的函数在执行,那么 Timer 的函数永远不会执行
Timer.run(() { print("executed"); }); // Will never be executed.
foo() {
scheduleMicrotask(foo); // Schedules [foo] in front of other events.
}
foo();
- unawaited //显示忽略Future的返回值
89-20.异常
- AsyncError
- DeferredLoadException
- ParallelWaitError
- TimeoutException
89-21.Future的扩展方法
future.ignore(); //忽略Future的返回
future.onError();
[Future.delayed(Duration())].wait; //同时等待Future的返回值
(int,int) ll = await (xx(),tt()).wait; //以记录的方式接受返回值,最多接收九个
90.String 类:UTF-16 代码单元序列
//单行字符串
'Single quotes';
"Double quotes";
'Double quotes in "single" quotes';
"Single quotes in 'double' quotes";
//多行字符串
'''A
multiline
string''';
"""
Another
multiline
string""";
//加号拼接
'Dart ' + 'is ' + 'fun!';
//相邻也可以拼接
'Dart ' 'is ' 'fun!';
- 构造
//参数是Unicode编码,Unicode 码点范围:0x0000 到 0x10FFFF(即 0 到 1114111),码点 0x0000 到 0xFFFF 对应基本多语言平面(BMP)字符,码点 0x10000 到 0x10FFFF 对应补充平面字符(如表情符号)
String.fromCharCode(charCode);
String.fromCharCodes();
String.fromEnvironment(name); // 获取编译时的参数,一般是 -d 后面的数据
- 属性
string.codeUnits; //每个字符的 UTF-16 代码单元
string.isEmpty;
string.isNotEmpty;
string.length; //注意有些比如unicode 如何 '\u{1D11E}' 实际长度会更短
string.runes; //此字符串的 Unicode 码位的 Iterable , 会合并成一个完整的整数
- 方法函数
string.allMatches(); //是否能匹配string整个字符串
string.codeUnitAt(); //获取某个字符的 UTF-16 代码单元
string.compareTo(); //比较uncode,区分大小写
string.contains();
string.endsWith();
string.indexOf();
string.lastIndexOf();
string.matchAsPrefix(); //从指定位置开始能否匹配成功,默认位置0
string.padLeft(); //如果长度少于指定值,在左侧添加以达到指定值,默认添加空格
string.padRight(); //如果长度少于指定值,在右侧添加以达到指定值,默认添加空格
string.replaceAll();
string.replaceAllMapped(); //对匹配到的做条件判断替换
string.replaceFirst();
string.replaceFirstMapped();
string.replaceRange();
string.split(); //使用''拆分获取每个字符
string.splitMapJoin();
string.startsWith();
string.substring();
string.toLowerCase();
string.toUpperCase();
string.trim();
string.trimLeft();
string.trimRight();
string * 3; //字符串还可以做乘法
string + string;
'\u{1D11E}'[0].codeUnits; //这种类型的字符串还有索引
91.StringBuffer 类
StringBuffer sb = StringBuffer();
sb.isEmpty;
sb.isNotEmpty;
sb.length;
sb.clear();
sb.toString();
sb.write(); // 参数未 null 会变成 "null"
sb.writeAll();
sb.writeCharCode();
sb.writeln(); // 在末尾添加换行
92.StringSink 使用他的实现者 ClosableStringSink IOSink StringBuffer
93.Symbol 类 ,可用于反射,动态标识类,方法和属性
import 'dart:mirrors';
class MyClass {
void myMethod() {
print('Hello from myMethod!');
}
}
void main() {
// 创建实例
MyClass myInstance = MyClass();
// 获取实例的反射对象
InstanceMirror instanceMirror = reflect(myInstance);
// 动态调用方法
Symbol methodName = #myMethod;
instanceMirror.invoke(methodName, []);
}
94.Type 类 标识运行时类型
95.Uri 类的使用
- 构造
//创建Uri
Uri();
Uri.https();
Uri.http();
//从文件创建Uri:如果不是文件类型,会报 UnsupportedError.
Uri.file(r'/home/myself/images/image.png', windows: false);
Uri.file(r'C:\Users\myself\Documents\image.png', windows: true);
Uri.directory('/home/myself/data/image', windows: false);
Uri.directory('/data/images', windows: true);
//从字符串创建Uri
final uri = Uri.parse(
'https://dart.dev/guides/libraries/library-tour#utility-classes');
//将小数据如图片字体,文本嵌入到Uri中,适应于web
final uri = Uri.dataFromBytes([68, 97, 114, 116]);
final uri = Uri.dataFromString();
- 属性
//协议+主机+端口:只针对http和https
uri.origin;
//主机+端口
uri.hasAuthority;
uri.authority;
//data:类型才有
uri.data;
// # 后面的内容
uri.isAbsolute //hasFragment 为 false 则 此为 true
uri.hasFragment;
uri.fragment;
//对于 / 符号后面是否有内容
uri.hasEmptyPath; //路径是否为空串
uri.hasAbsolutePath; //是否有以 / 开头的数据,不管 / 在哪个位置
//是否有端口
uri.hasPort;
uri.port;
//对于 ? 后面的数据
uri.hasQuery;
uri.query; // 原字符串,可能会进行编码
uri.queryParameters; // 解码后的数据,是一个Map
uri.queryParametersAll; // 解码后的数据,是一个Map,允许重复的key,重复key的value是一个数组 {"limit":["10","20","30"],"max":["100"]}
//协议
uri.hasScheme;
uri.scheme; // 转换成小写字母
//主机
uri.host; //不区分大小写,都转化为小写,并带有转义符
//路径
uri.path; //可能会对某些字符进行转义
uri.pathSegments; //不对特殊字符进行转义
//端口
uri.port; // 如果未指定的话有默认值 http 80 ,https 43 , 其他 0
//用户信息 协议://userInfo@主机
uri.userInfo; // https://username:password@example.com/path
- 方法函数
//是否为指定协议
uri.isScheme; //不必纠结于参数的大小写
uri.normalizePath(); //返回规范化的Uri,消除..相对路径,合并 /// 为 /
uri.removeFragment(); //移除 # 后面的字符串
uri.replace(); // 以覆盖原uri的某些部分创建新的uri
uri.resolve(); //解析相对Uri为绝对Uri
uri.resolveUri(); //解析相对Uri为绝对Uri
uri.toFilePath(); //专门用来解析文件类型的uri
- 静态属性
//如果是web,返回当前页面的url,否则返回当前工作目录
Uri.base;
- 静态方法函数
//解码Uri
Uri.decodeComponent();// 解析%部分 ,不解码分隔符,可能会改变原语义,导致Uri解析错误,如果要处理path和query,考虑使用 pathSegments 和 queryParameters
Uri.decodeFull(); //同上,但会解码分隔符
Uri.decodeQueryComponent(); //将+号转换成空格
Uri.parse(); //将字符串解析为Uri,失败会抛出异常
Uri.tryParse(); //将字符串解析为Uri,失败返回null
Uri.parseIPv4Address(host);
Uri.parseIPv6Address(host);
Uri.splitQueryString(host); //解码并拆分query部分数据
96.UriData 类的使用. 'data:' (type '/' subtype)? (';' attribute '=' value)* (';base64')? ',' data 示例: ( data:text/plain;charset=utf-8,Hello%20World! )
此类一般用于在Uri中加入数据如图片,文本
- 构造
UriData.fromBytes();
UriData.fromString();
UriData.fromUri();
- 属性
uriData.charset;
uriData.contentText;
uriData.isBase64;
uriData.mimeType;
uriData.parameters;
uriData.uri;
- 方法函数
uriData.contentAsBytes();
uriData.contentAsString();
uriData.isCharset(); //默认 charset=US-ASCII
uriData.isEncoding(); //默认 US-ASCII
uriData.isMimeType(mimeType); // 默认 text/plain
- 静态方法函数
//必须是相应的UriData格式
UriData.parse(uri);
97.WeakReference 弱引用,垃圾回收器运行并且没有其他引用使用他所包裹的值,就会被回收,可用来缓存数据
class CachedComputation<R extends Object> {
final R Function() computation;
WeakReference<R>? _cache;
CachedComputation(this.computation);
R get result {
final cachedResult = _cache?.target;
if (cachedResult != null) {
return cachedResult;
}
final result = computation();
// WeakReferences do not support nulls, bools, numbers, and strings.
if (result is! bool && result is! num && result is! String) {
_cache = WeakReference(result);
}
return result;
}
}
异常
ArgumentError
AssetionError
ConcurrentModificationError
Error
IndexError
NoSuchMethodError
OutOfMemoryError
ParallelWaitError
RangeError
StackOverflowError
StateError
TypeError
UnimplementedError
UnsupportedError
Exception
FormatException
dart:developer 库,用于开发人员工具(如调试器和检查器)交互。
dart:math 库:数学常数和函数,以及随机数生成器。
98. MutableRectangle 类:属性可变的二维矩形,过时了;移动端使用 dart:ui 的 Rect
99. Point 类:表示二维位置;移动端使用 dart:ui 的 Offset
100. Random 类:随机 bool、int 或 double 值的生成器。
var intValue = Random().nextInt(10); // Value is >= 0 and < 10.
intValue = Random().nextInt(100) + 50; // Value is >= 50 and < 150.
var doubleValue = Random().nextDouble(); // Value is >= 0.0 and < 1.0.
doubleValue = Random().nextDouble() * 256; // Value is >= 0.0 and < 256.0.
var boolValue = Random().nextBool(); // true or false, with equal chance.
101. Rectangle 类:二维矩形,过时了;移动端使用 dart:ui 的 Rect
102. 常量
e 自然对数的底数
ln10
ln2
log10e
log2e
pi
sqrt1_2
sqrt2
103. 函数
acos
asin
atan
atan2
cos
exp
log
max
min
pow
sin
sqrt
tan
dart:typed_data 库
dart🎯io 库:用于 file,socket,http ,io;注意:web 不用这个库
用于文件系统处理 FileSystemEntity
http服务器和客户端请求 HttpServer HttpClient
执行脚本 Process
web和服务器的全双工通信 WebSocket
tcp的套接字编程 Socket ServerSocket
标准用户输入,输出,错误输出 stdout stdin stderr
104. BytesBuilder 类 :构建和收集字节和字节集合
105. CompressionOptions 类:用户 WebSocket 的压缩选项
106. ConnectionTask 类:可取消的Socket链接包装类,用不了
107. ContentType 类:http传输内容类型的生成和解析
108. Cookie 类
109. Datagram 类
110. Directory 类
- 构造
Directory(); //如果参数是是相对路径,则其会以当前工作目录为基准,就像 Directory.current;
Directory.fromRawPath();
Directory.fromUri();
- 属性
myDir.absolute; //绝对路径
myDir.isAbsolute; //是否是绝对路径,以 Directory.current 为基准
myDir.parent;
myDir.path; //相对路径
myDir.uri; //如果是绝对路径,则返回的 Uri 的 scheme 始终为 file
- 方法函数
myDir.create();
myDir.createSync();
myDir.createTemp(); //在指定路径的目录下创建一个随机的子文件夹
myDir.createTempSync();
myDir.delete(); //删除失败会抛异常
myDir.deleteSync(); //删除失败会抛异常
myDir.exists();
myDir.existsSync();
myDir.list(); //列出子文件夹或文件,可递归
myDir.listSync();
myDir.rename(); //会删除当前的文件夹,并创建一个新的上一级文件夹同级别文件夹
myDir.renameSync();
myDir.resolveSymbolicLinks(); //用来处理 . .. 之类的
myDir.resolveSymbolicLinksSync();
myDir.stat(); //祥情信息
myDir.statSync();
myDir.watch(); //返回一个监听当前文件夹动态的流
- 静态属性
Directory.current; //当前工作目录
Directory.systemTemp; //用于系统创建临时工作目录的目录
111. File 类
var myFile = File('file.txt');
File('file.txt').readAsString().then((String contents) {
print(contents);
});
Stream<String> lines = file.openRead()
.transform(utf8.decoder) // Decode bytes to UTF-8.
.transform(LineSplitter()); // Convert stream to individual lines.
try {
await for (var line in lines) {
print('$line: ${line.length} characters');
}
print('File is now closed.');
} catch (e) {
print('Error: $e');
}
var file = await File(filename).writeAsString('some content');
var sink = file.openWrite();
sink.write('FILE ACCESSED ${DateTime.now()}\n');
await sink.flush();
// Close the IOSink to free system resources.
await sink.close();
var length = await file.length();
print(length);
final sink = File('/tmp').openWrite();
//监听写入完成的操作和写入时发生错误的操作
sink.done
.then((value){})
.catchError((e) {
// Handle the error.
});
sink.write("This is a test");
try {
// If one of these isn't awaited, then errors will pass silently!
await sink.flush();
await sink.close();
} on FileSystemException catch (e) {
print('Error writing file: $e');
}
//只是更改文件名
Future<File> changeFileNameOnly(File file, String newFileName) {
var path = file.path;
var lastSeparator = path.lastIndexOf(Platform.pathSeparator);
var newPath = path.substring(0, lastSeparator + 1) + newFileName;
return file.rename(newPath);
}
- 构造
File();
File.fromRawPath();
File.fromUri();
- 属性
file.absolute;
file.isAbsolute;
file.parent;
file.path;
file.uri; //如果是绝对路径,则返回的 Uri 的 scheme 始终为 file
- 方法函数
file.copy(); //复制文件
file.copySync();
file.create(); //第二个参数标志当文件存在时是否抛异常
file.createSync();
file.delete();
file.deleteSync();
file.exists();
file.existsSync();
file.lastAccessed(); //最后一次访问的时间
file.lastAccessedSync();
file.lastModified(); //最后一次更新的时间
file.lastModifiedSync();
file.length();
file.lengthSync();
file.open(); //通过标识打开一个可读可写的随机访问流
file.openSync();
file.openRead(); //整个读取
file.openWrite(); //可追加写入
file.readAsBytes(); //整个读取
file.readAsBytesSync();
file.readAsLines(); //一行一行读取成一个集合
file.readAsLinesSync();
file.readAsString(); //把整个内容一次性读取成一个字符串
file.readAsStringSync();
file.rename(); //最好全路径修改,否则将修改失败
file.renameSync();
file.setLastAccessed();
file.setLastAccessedSync();
file.setLastModified();
file.setLastModifiedSync();
file.writeAsBytes(); //如何参数 flush 为 true ,那么返回的 Future 将一定在数据写入文件之后
file.writeAsBytesSync();
file.writeAsString();
file.writeAsStringSync();
112. FileLock 类:请求锁定文件
113. FileMode 类:可以打开的文件的模式
- 常量
FileMode.append; //打开文件以进行读取和写入文件末尾的模式。如果文件尚不存在,则会创建该文件。
FileMode.read; //只读模式
FileMode.write; //打开文件进行读取和写入的模式。如果文件已存在,则该文件将被覆盖。如果文件尚不存在,则会创建该文件。
FileMode.writeOnly; //打开文件仅用于写入的模式。如果文件已存在,则该文件将被覆盖。如果文件尚不存在,则会创建该文件。
FileMode.writeOnlyAppend; //打开文件以仅写入文件末尾的模式。如果文件尚不存在,则会创建该文件。
114. FileStat 类:文件简介
- 属性
fileStat.accessed; //最后访问时间
fileStat.changed; //最后修改时间,windows平台是文件创建时间
fileStat.mode; //文件系统对象的模式,权限
fileStat.modified; //最后修改时间
fileStat.size; //文件大小
fileStat.type; //文件类型
- 方法函数
fileStat.modeString(); //用户、组和全局对读取、写入和执行文件系统对象的权限
- 静态方法
FileStat.stat();
FileStat.statSync();
115. FileSystemCreateEvent 类:文件创建监听
116. FileSystemDeleteEvent 类:文件删除监听
117. FileSystemEntity 类:文件,文件夹的父类
- 静态属性
FileSystemEntity.isWatchSupported; //当前系统是否支持检测文件系统动态
- 静态方法
FileSystemEntity.identical(); //检查两个路径是否引用文件系统中的同一对象
FileSystemEntity.identicalSync();
FileSystemEntity.isDirectory();
FileSystemEntity.isDirectorySync();
FileSystemEntity.isFile();
FileSystemEntity.isFileSync();
FileSystemEntity.isLink();
FileSystemEntity.isLinkSync();
FileSystemEntity.parentOf(); //当前路径的父路径
FileSystemEntity.type(); //当前路径的文件类型
FileSystemEntity.typeSync();
118. FileSystemEntityType 类:文件类型如 file, directory, or link.
- 常量
FileSystemEntityType.file;
FileSystemEntityType.directory;
FileSystemEntityType.link;
FileSystemEntityType.notFound;
FileSystemEntityType.pipe;
FileSystemEntityType.unixDomainSock;
119. FileSystemEvent 类:监听文件系统变化的类,一般使用子类:FileSystemCreateEvent FileSystemDeleteEvent FileSystemModifyEvent FileSystemMoveEvent
- 属性
fileSystemEvent.isDirectory;
fileSystemEvent.path;
fileSystemEvent.type; //时间类型
- 常量
FileSystemEvent.all;
FileSystemEvent.create;
FileSystemEvent.delete;
FileSystemEvent.modify;
FileSystemEvent.move;
120. FileSystemModifyEvent 类
- 属性
fileSystemModifyEvent.contentChanged; //如果内容而不是属性发生变化则为 true
121. FileSystemMoveEvent 类
- 属性
fileSystemMoveEvent.destination; //正在移动的目标路径
122. GZipCodec 类:将原始字节进行压缩和解压
https://api.dart.dev/stable/latest/dart-io/GZipCodec-class.html
- 构造
GZipCodec();
- 属性
gzipCodec.decoder; //解压对象
gzipCodec.dictionary; //初始压缩字典
gzipCodec.encoder; //压缩对象
gzipCodec.gzip; //压缩对象
gzipCodec.level; //压缩水平 -1..9 ,默认 6
gzipCodec.memLevel;
gzipCodec.raw;
gzipCodec.strategy;
gzipCodec.windowBits;
123. HeaderValue 类:表单中的头
HttpClientRequest request = ...;
var v = HeaderValue("text/plain", {"q": "0.3"});
request.headers.add(HttpHeaders.acceptHeader, v);
request.headers.add(HttpHeaders.acceptHeader, "text/html");
HttpRequest request = ...;
List<String> values = request.headers[HttpHeaders.acceptHeader];
values.forEach((value) {
HeaderValue v = HeaderValue.parse(value);
// Use v.value and v.parameters
});
- 构造
HeaderValue(); //params可为null
- 属性
headerValue.parameters; //其值无法增删改查
headerValue.value;
- 静态方法
HeaderValue.parse();
124. HttpClient 类
https://api.dart.dev/stable/latest/dart-io/HttpClient-class.html
- 构造
HttpClient();
- 属性
httpClient.authenticate; //返回 true 表示处理了认证,返回 false 表示没法处理该认证
httpClient.authenticateProxy;
httpClient.autoUncompress; //是否自动解压缩
httpClient.badCertificateCallback; //该回调将决定是否接受使用无法通过任何受信任的根证书进行身份验证的服务器证书的安全连接
httpClient.connectionFactory; //设置用于创建套接字的函数
httpClient.idleTimeout; //超时时间
httpClient.keyLog; //与服务器交换新 TLS 密钥时将调用的回调
httpClient.maxConnectionsPerHost; //获取并设置单个主机的最大实时连接数
httpClient.userAgent; //获取并设置此 HttpClient 生成的所有请求的 User-Agent 标头的默认值
- 方法函数
httpClient.addCredentials();
httpClient.addProxyCredentials();
httpClient.close(); //关闭连接,如果再尝试打开连接会抛异常
httpClient.delete(); //使用delete打开连接
httpClient.deleteUrl();
httpClient.get();
httpClient.getUrl();
httpClient.head();
httpClient.headUrl();
httpClient.open(); //以指定的请求方式打开http连接
httpClient.openUrl();
httpClient.patch();
httpClient.patchUrl();
httpClient.post();
httpClient.postUrl();
httpClient.put();
httpClient.putUrl();
- 静态属性
HttpClient.enableTimelineLogging; //客户端到服务端的时间线日志
- 静态方法
HttpClient.findProxyFromEnvironment(); //从系统环境中找寻代理
- 常量
HttpClient.defaultHttpPort; //80
HttpClient.defaultHttpsPort; //443
125. HttpClientBasicCredentials 类
https://api.dart.dev/stable/latest/dart-io/HttpClientBasicCredentials-class.html
- 构造
HttpClientBasicCredentials();
126. HttpClientCredentials 类
https://api.dart.dev/stable/latest/dart-io/HttpClientCredentials-class.html
127. HttpClientDigestCredentials 类
https://api.dart.dev/stable/latest/dart-io/HttpClientDigestCredentials-class.html
128. HttpClientRequest 类:继承自 IOSink
https://api.dart.dev/stable/latest/dart-io/HttpClientRequest-class.html
- 属性
request.bufferOutput; //是否使用缓存
request.connectionInfo; //获取连接信息
request.contentLength; //请求内容长度,默认-1
request.cookies;
request.done; //一旦有响应,将立即响应,适应于get请求
request.followRedirects;
request.headers;
request.maxRedirects;
request.method;
request.persistentConnection;
request.uri;
- 方法函数
request.abort(); //终止连接
request.close(); //关闭输入请求,返回done的值,通常用于post请求
129. HttpClientResponse 类:继承自 Stream
https://api.dart.dev/stable/latest/dart-io/HttpClientResponse-class.html
- 属性
response.certificate; //返回服务器的TLS和SSL证书,如果不安全则为 null
response.compressionState;
response.connectionInfo;
response.contentLength;
response.cookies;
response.headers; //不可变
response.isRedirect; //不可变
response.persistentConnection; //不可变
response.reasonPhrase; //返回与状态代码关联的原因短语
response.redirects;
response.statusCode;
- 方法函数
response.detachSocket();
response.redirect();
130. HttpConnectionInfo 类:连接信息
https://api.dart.dev/stable/latest/dart-io/HttpConnectionInfo-class.html
- 属性
info.localPort;
info.remoteAddress;
info.remotePort;
131. HttpConnectionsInfo 类:有关 HttpServers 当前套接字连接的摘要统计信息。
https://api.dart.dev/stable/latest/dart-io/HttpConnectionsInfo-class.html
- 构造
HttpConnectionsInfo();
- 属性
info.active; //活跃连接数
info.closing;
info.idle;
info.total;
132. HttpDate 类: 用于处理具有 HTTP 特定日期格式的日期的实用程序函数。
https://api.dart.dev/stable/latest/dart-io/HttpDate-class.html
- 构造
HttpDate();
- 静态方法
HttpDate.format(DateTime.now()); //Mon, 24 Mar 2025 03:17:16 GMT
HttpDate.parse();
133. HttpHeaders 类: 请求和响应的头
https://api.dart.dev/stable/latest/dart-io/HttpHeaders-class.html
- 属性
headers.chunkedTransferEncoding;
headers.contentLength;
headers.contentType;
headers.date;
headers.expires;
headers.host;
headers.ifModifiedSince;
headers.persistentConnection; //是否长连接 keep-alive
headers.port;
- 方法函数
headers.add(); //如果该头部字段已经存在,则会将新值添加到现有值的后面,形成多个值
headers.clear();
headers.forEach();
headers.noFolding();
headers.remove(); //移除指定name对应的单个value
headers.removeAll();
headers.set();
headers.value(); //获取指定name的头信息
- 常量
HttpHeaders.acceptCharsetHeader; //声明客户端能够接受的字符集编码类型。字符集编码是指对字符的编码方式,例如UTF-8、GBK等
HttpHeaders.acceptEncodingHeader; //声明客户端能够接受的编码方法,通常是指压缩方法,如gzip或deflate
HttpHeaders.acceptHeader;
HttpHeaders.acceptLanguageHeader;
HttpHeaders.acceptRangesHeader;
HttpHeaders.accessControlAllowCredentialsHeader;
HttpHeaders.accessControlAllowHeadersHeader;
HttpHeaders.accessControlAllowMethodsHeader;
HttpHeaders.accessControlAllowOriginHeader;
HttpHeaders.accessControlExposeHeadersHeader;
HttpHeaders.accessControlMaxAgeHeader;
HttpHeaders.accessControlRequestHeadersHeader;
HttpHeaders.accessControlRequestMethodHeader;
HttpHeaders.ageHeader;
HttpHeaders.allowHeader;
HttpHeaders.authorizationHeader;
HttpHeaders.cacheControlHeader;
HttpHeaders.connectionHeader;
HttpHeaders.contentDisposition;
HttpHeaders.contentEncodingHeader;
HttpHeaders.contentLanguageHeader;
HttpHeaders.contentLengthHeader;
HttpHeaders.contentLocationHeader;
HttpHeaders.contentMD5Header;
HttpHeaders.contentRangeHeader;
HttpHeaders.contentTypeHeader;
HttpHeaders.cookieHeader;
HttpHeaders.dateHeader;
HttpHeaders.entityHeaders;
HttpHeaders.etagHeader;
HttpHeaders.expectHeader;
HttpHeaders.expiresHeader;
HttpHeaders.fromHeader;
HttpHeaders.generalHeaders;
HttpHeaders.hostHeader;
HttpHeaders.ifMatchHeader;
HttpHeaders.ifModifiedSinceHeader;
HttpHeaders.ifNoneMatchHeader;
HttpHeaders.ifRangeHeader;
HttpHeaders.ifUnmodifiedSinceHeader;
HttpHeaders.lastModifiedHeader;
HttpHeaders.locationHeader;
HttpHeaders.maxForwardsHeader;
HttpHeaders.pragmaHeader;
HttpHeaders.proxyAuthenticateHeader;
HttpHeaders.proxyAuthorizationHeader;
HttpHeaders.rangeHeader;
HttpHeaders.refererHeader;
HttpHeaders.requestHeaders;
HttpHeaders.responseHeaders;
HttpHeaders.retryAfterHeader;
HttpHeaders.serverHeader;
HttpHeaders.setCookieHeader;
HttpHeaders.teHeader;
HttpHeaders.trailerHeader;
HttpHeaders.transferEncodingHeader;
HttpHeaders.upgradeHeader;
HttpHeaders.userAgentHeader;
HttpHeaders.varyHeader;
HttpHeaders.viaHeader;
HttpHeaders.warningHeader;
HttpHeaders.wwwAuthenticateHeader;
134. HttpOverrides 类:用于 全局拦截和自定义 HTTP/HTTPS 请求行为 的类。它允许开发者覆盖 Dart 默认的 HTTP 客户端实现
https://api.dart.dev/stable/latest/dart-io/HttpOverrides-class.html#constructors
135. HttpRequest 类
https://api.dart.dev/stable/latest/dart-io/HttpRequest-class.html
final HOST = InternetAddress.loopbackIPv4;
final PORT = 80;
HttpServer.bind(HOST, PORT).then((_server) {
_server.listen((HttpRequest request) {
switch (request.method) {
case 'GET':
handleGetRequest(request);
break;
case 'POST':
...
}
},
onError: handleError); // listen() failed.
}).catchError(handleError);
void handleGetRequest(HttpRequest req) {
HttpResponse res = req.response;
res.write('Received request ${req.method}: ${req.uri.path}');
res.close();
}
- 属性
httpRequest.certificate; //发出请求的客户端的客户端证书
httpRequest.connectionInfo;
httpRequest.contentLength;
httpRequest.cookies; //从Cookie请求头获取
httpRequest.headers;
httpRequest.method;
httpRequest.persistentConnection;
httpRequest.protocolVersion;
httpRequest.requestedUri; //客户端请求的原始路径
httpRequest.response;
httpRequest.session;
httpRequest.uri; //服务器当前处理的路径,可能被重定向
136. HttpResponse 类
https://api.dart.dev/stable/latest/dart-io/HttpResponse-class.html
server.listen((HttpRequest request) {
request.response.write('Hello, world!');
request.response.close(); //发送到客户端
});
- 属性
httpResponse.bufferOutput;
httpResponse.connectionInfo;
httpResponse.contentLength;
httpResponse.cookies;
httpResponse.deadline; //响应的截止时间
httpResponse.headers;
httpResponse.persistentConnection;
httpResponse.reasonPhrase; //写入正文之前设置
httpResponse.statusCode; //写入正文之前设置
- 方法函数
httpResponse.detachSocket();
httpResponse.redirect();
137. HttpServer 类
https://api.dart.dev/stable/latest/dart-io/HttpServer-class.html
import 'dart:io';
// ssl的http连接
void main() async {
var chain =
Platform.script.resolve('certificates/server_chain.pem').toFilePath();//pem文件可以通过openssl获取
var key = Platform.script.resolve('certificates/server_key.pem').toFilePath();
var context = SecurityContext()
..useCertificateChain(chain)
..usePrivateKey(key, password: 'dartdart');
var server =
await HttpServer.bindSecure(InternetAddress.anyIPv6, 443, context);
await server.forEach((HttpRequest request) {
request.response.write('Hello, world!');
request.response.close();
});
}
- 构造
HttpServer.listenOn(); //关联HttpServer和serverSocket
- 属性
httpServer.address;
httpServer.autoCompress;
httpServer.defaultResponseHeaders;
httpServer.idleTimeout; //获取或设置用于空闲 keep-alive 连接的超时
httpServer.port;
httpServer.serverHeader;
httpServer.sessionTimeout;
- 方法函数
httpServer.close();
httpServer.connectionsInfo(); //汇总服务器处理的当前连接数。
- 静态方法
HttpServer.bind();
HttpServer.bindSecure();
138. HttpSession 类:在服务器上存储有关浏览器会话的任意信息。此信息存储在内存中,因此当服务器退出时,它将丢失
https://api.dart.dev/stable/latest/dart-io/HttpSession-class.html
import 'dart:io';
void main() async {
HttpServer.bind("localhost", 8080).then((server) {
server.listen((request) {
final session = request.session;
if (session.isNew) {
session["cart"] = [];
}
if (request.uri.queryParameters['buy'] != null) {
final item = request.uri.queryParameters['buy'];
session["cart"].add(item);
}
session["cart"].cast<String>().forEach(request.response.writeln);
request.response.close();
});
});
}
- 属性
httpSession.id;
httpSession.isNew;
httpSession.onTimeout;
- 方法函数
httpSession.destroy();
139. HttpStatus 类
https://api.dart.dev/stable/latest/dart-html/HttpStatus-class.html
- 常量
HttpStatus.accepted; //202
HttpStatus.alreadyReported; //208
HttpStatus.badGateway; //502
HttpStatus.badRequest; //400
HttpStatus.clientClosedRequest; //499
HttpStatus.conflict; //409
HttpStatus.connectionClosedWithoutResponse; //444
HttpStatus.continue_; //100
HttpStatus.created; //201
HttpStatus.expectationFailed; //417
HttpStatus.failedDependency; //424
HttpStatus.forbidden; //403
HttpStatus.found; //302
HttpStatus.gatewayTimeout; //504
HttpStatus.gone; //410
HttpStatus.httpVersionNotSupported; //505
HttpStatus.imUsed; //226
HttpStatus.insufficientStorage; //507
HttpStatus.internalServerError; //500
HttpStatus.lengthRequired; //411
HttpStatus.locked; //423
HttpStatus.loopDetected; //508
HttpStatus.methodNotAllowed; //405
HttpStatus.misdirectedRequest; //421
HttpStatus.movedPermanently; //301
HttpStatus.movedTemporarily; //302
HttpStatus.multipleChoices; //300
HttpStatus.multiStatus; //207
HttpStatus.networkAuthenticationRequired; //511
HttpStatus.networkConnectTimeoutError; //599
HttpStatus.noContent; //204
HttpStatus.nonAuthoritativeInformation; //203
HttpStatus.notAcceptable; //406
HttpStatus.notExtended; //510
HttpStatus.notFound; //404
HttpStatus.notImplemented; //501
HttpStatus.notModified; //304
HttpStatus.ok; //200
HttpStatus.partialContent; //206
HttpStatus.paymentRequired; //402
HttpStatus.permanentRedirect; //308
HttpStatus.preconditionFailed; //412
HttpStatus.preconditionRequired; //428
HttpStatus.processing; //102
HttpStatus.proxyAuthenticationRequired; //407
HttpStatus.requestedRangeNotSatisfiable; //416
HttpStatus.requestEntityTooLarge; //413
HttpStatus.requestHeaderFieldsTooLarge; //431
HttpStatus.requestTimeout; //408
HttpStatus.requestUriTooLong; //414
HttpStatus.resetContent; //205
HttpStatus.seeOther; //303
HttpStatus.temporaryRedirect; //307
HttpStatus.tooManyRequests; //429
HttpStatus.unauthorized; //401
HttpStatus.unavailableForLegalReasons; //451
HttpStatus.unprocessableEntity; //422
HttpStatus.unsupportedMediaType; //415
HttpStatus.upgradeRequired; //426
HttpStatus.useProxy; //305
HttpStatus.variantAlsoNegotiates; //506
140. InternetAddress 类
https://api.dart.dev/stable/latest/dart-io/InternetAddress-class.html
- 构造
InternetAddress();
InternetAddress.fromRawAddress();
- 属性
internetAddress.address;
internetAddress.host;
internetAddress.isLinkLocal;
internetAddress.isLoopback;
internetAddress.isMulticast;
internetAddress.rawAddress;
internetAddress.type;
- 方法函数
internetAddress.reverse();
- 静态属性
InternetAddress.anyIPv4;
InternetAddress.anyIPv6;
InternetAddress.loopbackIPv4;
InternetAddress.loopbackIPv6;
- 静态方法
InternetAddress.lookup();
InternetAddress.tryParse(); //尝试解析为数字地址
141. InternetAddressType 类
https://api.dart.dev/stable/latest/dart-io/InternetAddressType-class.html
- 属性
InternetAddressType.name;
- 常量
InternetAddressType.any;
InternetAddressType.IPv4;
InternetAddressType.IPv6;
InternetAddressType.unix;
142. IOOverrides 类
https://api.dart.dev/stable/latest/dart-io/IOOverrides-class.html
143. IOSink 类
https://api.dart.dev/stable/latest/dart-io/IOOverrides-class.html
- 构造
IOSink();
- 属性
ioSink.done; //将在使用者关闭或发生错误时完成的 future。这个 future 与 close 返回的 future 相同。
ioSink.encoding;
- 方法函数
ioSink.add();
ioSink.addError();
ioSink.addStream();
ioSink.close(); //调用这个方法不会刷新缓冲,必须在这之前调用flush()
ioSink.flush();
ioSink.write();
ioSink.writeAll();
ioSink.writeCharCode();
ioSink.writeln();
144. Link 类:主要用于文件系统相关
145. NetworkInterface 类:表示当前系统上的活动网络接口。它包含绑定到接口的 InternetAddresses 列表
146. Pipe 类:macos和linux的进程间通信
147. Platform 类:当前程序运行的环境信息
- 静态方法
Platform.environment; //当前系统的环境信息,win不区分大小写
Platform.executable; //运行此脚本的可执行文件路径
Platform.executableArguments; //运行此脚本的可执行文件的执行参数
Platform.isAndroid; //当前环境是否是 Android
Platform.isFuchsia;
Platform.isIOS;
Platform.isLinux;
Platform.isMacOS;
Platform.isWindows;
Platform.lineTerminator; //分隔或终止文本行的默认字符序列
Platform.localeName; //当前本地化的名称
Platform.localHostname; //系统的本地主机名
Platform.numberOfProcessors; //可执行线程数量
Platform.operatingSystem; //操作系统名
Platform.operatingSystemVersion; //操作系统版本
Platform.packageConfig; //操作系统版本
Platform.pathSeparator; //系统路径分隔符
Platform.resolvedExecutable; //运行脚本的可执行文件的绝对路径
Platform.script; //运行的脚本的绝对 URI
Platform.version; //当前 Dart 运行时的版本
148. Process 类:执行程序的方法
var process = await Process.start('cat', []);
process.stdout
.transform(utf8.decoder)
.forEach(print);
process.stdin.writeln('Hello, world!');
process.stdin.writeln('Hello, galaxy!');
process.stdin.writeln('Hello, universe!');
stdout.addStream(process.stdout);
- 属性
process.exitCode; //退出码,正常退出是正值
process.pid;
process.stderr; //程序的标准错误流
process.stdin; //程序的标准输入流
process.stdout; //程序的标准输出流
- 方法函数
process.kill();
- 静态方法
Process.killPid(); //杀掉进程
Process.run(); //启动一个进程,并以非交互方式运行该进程直至完成
Process.runSync();
Process.start(); //启动一个进程,并以交互方式运行该进程
149. ProcessInfo 类:检索进程信息
- 静态属性
ProcessInfo.currentRss;
ProcessInfo.maxRss;
150. ProcessResult 类:Process.run 或 Process.runSync 启动的非交互式进程的运行结果
- 构造
ProcessResult.new(int pid, int exitCode, dynamic stdout, dynamic stderr)
- 属性
processResult.exitCode;
processResult.pid;
processResult.stderr;
processResult.stdout;
151. ProcessSignal 类:用于向子进程发送特定信号
152. ProcessStartMode 类:开启新进程的模式
- 常量
ProcessStartMode.detached;
ProcessStartMode.detachedWithStdio;
ProcessStartMode.inheritStdio;
ProcessStartMode.normal;
153. RandomAccessFile 类:文件中数据的随机访问,通过 file.open() 获得
- 属性
randomAccessFile.path; //底层的文件路径
randomAccessFile.close(); //关闭文件
randomAccessFile.closeSync();
randomAccessFile.flush(); //将文件的内容刷新到磁盘
randomAccessFile.flushSync();
randomAccessFile.length(); //文件的字节长度
randomAccessFile.lengthSync();
randomAccessFile.lock([ FileLock mode = FileLock.exclusive, int start = 0, int end = -1 ]);
randomAccessFile.lockSync([ FileLock mode = FileLock.exclusive, int start = 0, int end = -1 ]);
randomAccessFile.position(); //获取游标在文件中的位置
randomAccessFile.positionSync();
randomAccessFile.read( int count ); //读取指定长度的字节数据
randomAccessFile.readSync( int count );
randomAccessFile.readByte(); //读取一个字节,空数据会返回-1
randomAccessFile.readByteSync();
randomAccessFile.readInto( List<int> buffer, [ int start = 0, int? end ]); //将字节读取到现有缓冲区中
randomAccessFile.readIntoSync( List<int> buffer, [ int start = 0, int? end ]);
randomAccessFile.setPosition( int position ); //设置游标的位置
randomAccessFile.setPositionSync( int position );
randomAccessFile.toString();
randomAccessFile.truncate( int length ); //将文件截断(或扩展)到指定的字节长度
randomAccessFile.truncateSync( int length );
randomAccessFile.unlock([ int start = 0, int end = -1 ]);
randomAccessFile.unlockSync([ int start = 0, int end = -1 ]);
randomAccessFile.writeByte( int value ); //写入一个字节
randomAccessFile.writeByteSync( int value );
randomAccessFile.writeFrom( List<int> buffer, [ int start = 0, int? end ]); //写入buffer
randomAccessFile.writeFromSync( List<int> buffer, [ int start = 0, int? end ]);
randomAccessFile.writeString(String string, {Encoding encoding = utf8,}); //写入字符串
randomAccessFile.writeStringSync(String string, {Encoding encoding = utf8,});
154. RawDatagramSocket 类:一个未缓存的UDP套接字接口
155. RawSecureServerSocket 类:一个提供低级 RawSecureSockets 流的服务器套接字
https://api.dart.dev/dart-io/RawSecureServerSocket-class.html
156. RawSecureSocket 类:提供一个安全的 (SSL 或 TLS) 网络连接
157. RawServerSocket 类:一个监听套接字
158. RawSocket 类:一个 TCP 连接
159. RawSocketEvent 类:RawDatagramSocket、RawSecureSocket 和 RawSocket 的事件
160. RawSocketOption 类:RawSocketOption 用作 Socket.setRawOption 和 RawSocket.setRawOption 的参数
161. RawSynchronousSocket 类:一个用于通过TCP套接字进行同步通信的低级类
https://api.dart.dev/dart-io/RawSynchronousSocket-class.html
162. RawZLibFilter 类:RawZLibFilter 类提供了 zlib 的低级接口
163. ReadPipe 类:由 Pipe.create 创建的管道的 "读" 端
164. RedirectInfo 类:重定向信息
165. ResourceHandle 类:一个包装器,围绕操作系统资源句柄,以便可以通过Socket作为SocketMessage的一部分进行传递
166. SameSite 类:Cookie跨站点可用性配置
167. SecureServerSocket 类:一个服务器套接字,提供高层套接字的流
168. SecureSocket 类:一个使用TLS和SSL的TCP套接字
169. SecurityContext 类:用于进行安全客户端连接的可信证书的对象,以及用于从安全服务器提供的证书链和私钥
170. ServerSocket 类:一个监听套接字
171. Socket 类:两个套接字之间的 TCP 连接。套接字连接将本地套接字连接到远程套接字。数据(作为 Uint8Lists)由本地套接字接收
172. SocketControlMessage 类:通过调用 RawSocket.readMessage 接收到的 SocketMessage 的控制消息部分
https://api.dart.dev/dart-io/SocketControlMessage-class.html
173. SocketDirection 类:在指定方向上关闭一个 socket
174. SocketMessage 类:由 RawDatagramSocket 接收到的套接字消息
175. SocketOption 类:一个用于配置套接字的选项,可以通过 Socket.setOption 进行设置
176. Stdin 类:进程的标准输入流。允许从标准输入流进行同步和异步读取
177. StdioType 类:标准IO流可以连接的对象类型
178. Stdout 类:一个 IOSink 连接到进程的标准 out 或 error
179. SystemEncoding 类:系统编码是在 Windows 上的当前代码页,以及在 Linux 和 Mac 上的 UTF-8
180. TlsProtocolVersion 类:传输层安全性(TLS)版本
181. WebSocket 类:一个用于客户端或服务器应用程序的双向HTTP通信对象
182. WebSocketStatus 类:关闭WebSocket连接时使用的WebSocket状态码
183. WebSocketTransformer 类:WebSocketTransformer 提供将 HttpRequest 升级到 WebSocket 连接的能力
https://api.dart.dev/dart-io/WebSocketTransformer-class.html
184. WritePipe 类:由 Pipe.create 创建的管道的“写入”端
185. X509Certificate 类:X509Certificate 代表一个 SSL 证书,具有访问器以获取证书字段
186. ZLibCodec 类:ZLibCodec 将原始字节编码为 ZLib 压缩字节,并将 ZLib 压缩字节解码为原始字节
187. ZLibDecoder 类:ZLibDecoder 被 ZLibCodec 和 GZipCodec 用来解压数据
188. ZLibEncoder 类:ZLibEncoder 编码器被 ZLibCodec 和 GZipCodec 用于压缩数据
189. ZLibOption 类:暴露了 ZLib 选项以供输入参数使用
190. HttpClientResponseCompressionState 类:指定 HttpClientResponse 的字节流的压缩状态
https://api.dart.dev/dart-io/HttpClientResponseCompressionState.html
191. dart:io 库中的顶级常量
- gzip :GZipCodec的默认实现的一个实例。
- systemEncoding :当前系统编码
- zlib :ZLibCodec 默认实现的一个实例
192. dart:io 库中的顶级属性
- exitCode :获取 Dart VM 的全局退出代码
- pid :返回当前进程的PID
- stderr :此程序输出的标准错误流
- stdin :该程序读取的标准输入数据流
- stdout :此程序写入的数据的标准输出流
193. dart:io 库中的顶级函数
- exit() :立即退出 Dart VM 进程,使用给定的退出代码 [0...127]
- sleep() :在指定的持续时间内使用 OnSleep。请谨慎使用,因为在隔离被阻塞在睡眠调用时,无法处理任何异步操作
- stdioType() :是否一个流是连接到文件、管道、终端还是其他什么
194. dart:io 库中的类型定义
- BadCertificateCallback
195. dart:io 库中的异常
- CertificateException
- FileSystemException
- HandshakeException
- HttpException
- IOException
- OSError
- PathAccessException
- PathExistsException
- PathNotFoundException
- ProcessException
- RedirectException
- SignalException
- SocketException
- StdinException
- StdoutException
- TlsException
- WebSocketException
dart:isolate 库:使用隔离体的并发编程:独立的工作者,类似于线程但不共享内存,仅通过消息进行通信
196. Capability 类:一个不可伪造的对象,通过其他隔离区传递后会返回相等的值
197. Isolate 类:一个孤立的 Dart 执行上下文。所有 Dart 代码都在一个孤立中运行,代码只能访问来自同一孤立的类和变量
198. RawReceivePort 类:一个低级异步消息接收器
199. ReceivePort 类:与 SendPort 一起,是隔离之间的唯一通信手段
200. SendPort 类:向其接收端发送消息
201. TransferableTypedData 类:一个有效可转移的字节值序列
https://api.dart.dev/dart-isolate/TransferableTypedData-class.html
202. dart:isolate 库中的异常
- IsolateSpawnException
- RemoteError
dart:mirrors 库:Dart中的基本反射,支持自省和动态调用
203. ClassMirror 类:ClassMirror 反映了 Dart 语言的一个类
204. ClosureMirror 类:闭包镜像反映一个闭包
205. CombinatorMirror 类:一个声明在库依赖上的显示/隐藏组合器的镜像
https://api.dart.dev/dart-mirrors/CombinatorMirror-class.html
206. CombinatorMirror 类:声明镜像反映了在Dart程序中声明的某个实体。
https://api.dart.dev/dart-mirrors/DeclarationMirror-class.html
207. FunctionTypeMirror 类
https://api.dart.dev/dart-mirrors/FunctionTypeMirror-class.html
208. InstanceMirror 类
209. IsolateMirror 类
210. LibraryDependencyMirror 类
https://api.dart.dev/dart-mirrors/LibraryDependencyMirror-class.html
211. LibraryMirror 类
212. MethodMirror 类
213. Mirror 类
214. MirrorSystem 类
215. ObjectMirror 类
216. ParameterMirror 类
https://api.dart.dev/dart-mirrors/ParameterMirror-class.html
217. SourceLocation 类
218. TypedefMirror 类
219. TypeMirror 类
220. TypeVariableMirror 类
https://api.dart.dev/dart-mirrors/TypeVariableMirror-class.html
221. VariableMirror 类
222. dart:mirrors 库中的顶级函数
- currentMirrorSystem();
- reflect() : 反映一个实例。返回一个反映反射对象的 InstanceMirror
- reflectClass() : 反映类声明。让 C 成为由 key 表示的类的原始类声明
- reflectType() : 反映由键表示的类型。如果键不是 Type 的实例,则此函数会抛出 ArgumentError
223. dart:mirrors 库中的异常
- AbstractClassInstantiationError

浙公网安备 33010602011771号