
1.flutter是一个单线程,eventloop事件循环。支持Isolate
async await 异步请求非阻塞式的调用 Future

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
class ZFLAsyncThreadPage extends StatefulWidget {
@override
_ZFLAsyncThreadPageState createState() => _ZFLAsyncThreadPageState();
}
class _ZFLAsyncThreadPageState extends State<ZFLAsyncThreadPage> {
List<dynamic> datas = [];
@override
void initState() {
super.initState();
loadData();
}
@override
Widget build(BuildContext context) {
return Container(
child: ListView.builder(
itemCount: datas.length,
itemBuilder: (BuildContext context, int index){
return Text('${datas[index]}');
}),
);
}
loadData() async{
String url = 'https://jsonplaceholder.typicode.com/posts';
http.Response response = await http.get(url);
datas = json.decode(response.body);
setState(() {
});
}
}
2.Future和非Future。
//非Future
String getNetworkData() {
print('请求中');
sleep(Duration(seconds: 2));
return "执行完成";
// var result = getNetworkData();
// print(result);
// print("main end");
//I/flutter ( 7143): 请求中
//I/flutter ( 7143): 执行完成
//I/flutter ( 7143): main end
}
//Future
Future getNetworkDataHasFuture() async {
print('请求中');
return Future(() {
sleep(Duration(seconds: 2));
return "执行完成";
});
}
// var result = getNetworkDataHasFuture();
// result.then((value){
// print(value);
// });
// print(result);
// print("main end");
// I/flutter ( 7419): 请求中
// I/flutter ( 7419): Instance of 'Future<dynamic>'
// I/flutter ( 7419): main end
// I/flutter ( 7419): 执行完成
3.把工作放到后台线程执行。
分离的运行线程,不能访问主线程的变量,isolate不能共享内存。
如果执行长时间复杂任务,避免阻塞 event loop。
如果一个方法要花费几毫秒时间那么建议使用 Future 。
如果一个处理可能需要几百毫秒那么建议使用 isolate 。
rootIsolate和newIsolate之间的通信必须要暴露一个端口,必须知道彼此的端口。
//后台请求接口
backGroundLoadData() async{
ReceivePort rootIsolate = ReceivePort();//rootIsolate
//为的是让newIsolate中持有rootIsolateSendPort 这样在newIsolate中就能向rootIsolate发送消息了
await Isolate.spawn(dataLoader, rootIsolate.sendPort);//rootIsolateSendPort
SendPort sendPort = await rootIsolate.first;//新的ReceivePort
ReceivePort rootIsolateResponse = ReceivePort(); //第一个元素回收后监听会关闭,所以要新创建一个rootIsolateResponse
sendPort.send(["https://jsonplaceholder.typicode.com/posts",rootIsolateResponse.sendPort]);
List msg = await rootIsolateResponse.first;
print(msg);
}
//newIsolate
static dataLoader(SendPort rootSendPort) async {
ReceivePort port = ReceivePort();//newIsolateReceivePort
rootSendPort.send(port.sendPort);
await for(var msg in port) {
String data = msg[0];
SendPort replyTo = msg[1];
String dataUrl = data;
http.Response response = await http.get(dataUrl);
replyTo.send(json.decode(response.body));
}
}
网友评论