云起工作室 15711107967
10_网络请求
2025-02-06 10:44:21

http 和dio

http

加载

http包官网使 pub.dev

网络请求有两个 一个使dio 一个是http

http包地址:https://pub.dev/packages/http


在pubspec.yml 文件里 输入

在dependencies:包含的最下方

http: ^1.2.1

点击pub get


使用

import 'package:http/http.dart' as http

定义网络方法

getDatas() async {

final url=Uri.parse("接口地址");

final response = await http.get(url);

//print(response.statusCode) //200

print(response.body)

}


使用

getDatas()

或者

child: FutureBuilder(

future: getDatas(),

builder: (BuildContext context, AsyncSnapshot snapshot) {

print("dddd");

print(snapshot);

if(snapshot.connectionState == ConnectionState.waiting){

return Text("loading");

}

return Container();

},

),



异步请求使用


定义

Future<List> getList() async{

final url = Uri("/api/porjectlist");

final response = await http.get(url);

if(response.statusCode==200){

return json.decode(response.body)['list'];

}else{

throw Exception("errorcode");

}

}

使用

getList().then((val){

})


dio

加载

在pubspec.yaml里

dependencies下

dio:^4.0.1

使用

import “package:dio/dio.dart”

final dio = Dio();

dio.get("api/projectlist").then((val){}) get请求

dio.download("下载地址","保存路径/文件名称").then((value){}); 下载


第二个参数可以是路径的字符串,也可以是回调函数

手机端路径获取

String path = Dorectory.systemTemp.path+"/文件名称";

dio.download(url,(header){

return path

},onReveiveProgress:showDownloadProgress)

.whenComplete((){}).catchError((e){})

void showDownloadProgress(int count,int total){}