Object x = "hi world";
// The getter 'length' is not defined for the class 'Object'
print(x.length);
函数也是一个对象,是一个Function类型,所以可用于参数,如果没有写返回值类型,默认会为dynamic。所以要注意函数返回值没有类型推断,如果作为参数最好要确定好返回值类型
var say = (str){
print(str);
};
say("hi world");
void execute(var callback) {
callback();
}
execute(() => print("xxx"))
say(str,[a,b])
void say({bool bold, bool hidden}) {}
当Future内执行完毕后会调用then,如果出现任何异常(包括代码错误)也会执行catchError,不管成功失败走回走whenComplete。
Future.wait的作用是等待多个异步任务全部执行完毕后再回调。
Future.wait([
// 2秒后返回结果
Future.delayed(new Duration(seconds: 2), () {
return "hello";
}),
// 4秒后返回结果
Future.delayed(new Duration(seconds: 4), () {
return " world";
})
]).then((results){
print(results[0]+results[1]);
}).catchError((e){
print(e);
});
///get请求
static Future get(String url, [Map params]) async {
Response response;
if (params != null) {
response = await dio.get(url, queryParameters: params);
} else {
response = await dio.get(url);
}
return response.data;
}
///use
get('api', {
"a": 'b',
}).then((response) {
//执行成功后
}).catchError((onError) {
//任何失败
}).whenComplete((){
//无论成功或失败都会走到这里
});
其实,无论是在JavaScript还是Dart中,async/await都只是一个语法糖,编译器或解释器最终都会将其转化为一个Promise(Future)的调用链
Stream 也是用于接收异步事件数据,但不同点在于可以多次接收触发回调。
import 'dart:async';
import 'package:event_bus/event_bus.dart';
//EventBus工具类
class XEvent {
XEvent._internal();
static Map sEventPool = {};
static Map> sStreamPool = {};
static EventBus getEvent(String eventName, {bool isSync = false}) {
EventBus event = sEventPool[eventName];
if (event == null) {
event = new EventBus(sync: isSync);
sEventPool[eventName] = event;
}
return event;
}
//订阅信息, 默认是异步的
static StreamSubscription on(String eventName, void onData(T event),
{bool isSync = false,
Function onError,
void onDone(),
bool cancelOnError}) {
StreamSubscription stream = getEvent(eventName, isSync: isSync)
.on()
.listen(onData,
onError: onError, onDone: onDone, cancelOnError: cancelOnError);
List streams = sStreamPool[eventName];
if (streams == null) {
streams = [];
streams.add(stream);
sStreamPool[eventName] = streams;
} else {
streams.add(stream);
}
return stream;
}
//事件发送
static void post(String eventName, event) {
EventBus eventBus = getEvent(eventName);
eventBus.fire(event);
}
//根据事件名取消
static void cancelWithName(String eventName) {
List streams = sStreamPool[eventName];
if (streams != null) {
for (StreamSubscription item in streams) {
item.cancel();
}
streams.clear();
}
}
//根据订阅实例取消
static void cancel(String eventName, StreamSubscription subscription) {
if (subscription == null) return;
List streams = sStreamPool[eventName];
if (streams != null) {
subscription.cancel();
streams.remove(subscription);
}
}
}
// 导入核心库
import 'dart:math';
// 从外部 Package 中导入库
import 'package:test/test.dart';
// 导入文件
import 'path/to/my_other_file.dart';
class Spacecraft {
String name;
DateTime launchDate;
// 构造函数,带有可以直接为成员变量赋值的语法糖。
Spacecraft(this.name, this.launchDate) {
// 这里可以实现初始化代码。
}
// 命名构造函数,转发到默认构造函数。
Spacecraft.unlaunched(String name) : this(name, null);
int get launchYear =>
launchDate?.year; // 只读的非 final 的属性
// 方法。
void describe() {
print('宇宙飞船:$name');
if (launchDate != null) {
int years =
DateTime.now().difference(launchDate).inDays ~/
365;
print('发射时间:$launchYear ($years years ago)');
} else {
print('尚未发射');
}
}
}
class Orbiter extends Spacecraft {
double altitude;
Orbiter(String name, DateTime launchDate, this.altitude)
: super(name, launchDate);
}
class Manager {
// 工厂模式
factory Manager() =>_getInstance()
static Manager get instance => _getInstance();
static Manager _instance;
Manager._internal() {
// 初始化
}
static Manager _getInstance() {
if (_instance == null) {
_instance = new Manager._internal();
}
return _instance;
}
}
使用
// 无论如何初始化,取到的都是同一个对象
Manager manager = new Manager();
Manager manager2 = Manager.instance;