[Flutter] http和Dio插件实现网络请求
http和dio实现网络请求
http:
配置依赖
#网络请求
http: ^0.13.4
导入包
import 'package:http/http.dart' as http;
声明一个列表存储请求返回的数据
List _list = [];
声明请求方法
_getData() async {
var apiUrl = Uri.parse('https://jdmall.itying.com/api/pcate');
var response = await http.get(apiUrl);
setState(() {
//response.body的类型是String。
_list = json.decode(response.body)['result'];
});
}
初始化方法
@override
void initState() {
super.initState();
_getData();
}
使用请求的数据
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('请求数据'),
),
body: _list.isNotEmpty
? ListView.builder(
itemCount: _list.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(_list[index]['title']),
);
})
: const Text('正在请求...'),
);
}
}
Dio:
配置依赖
dio: ^4.0.4
导入包
import 'package:http/http.dart' as http;
声明一个列表存储请求返回的数据
List _list = [];
定义请求数据的方法
_getData() async {
var response = await Dio().get('https://jdmall.itying.com/api/pcate');
if (response.statusCode == 200) {
print(response.data);
setState(() {
_list = response.data['result'];
});
} else {
print('Response status:${response.statusCode}');
}
print('${response.data}');
}
初始化方法
@override
void initState() {
super.initState();
_getData();
}
使用
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('请求数据'),
),
body: _list.isNotEmpty
? ListView.builder(
itemCount: _list.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(_list[index]['title']),
);
})
: const Text('正在请求...'),
);
}
}
分类:
Flutter学习
« 上一篇: [Flutter] Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
» 下一篇: [Flutter]Unhandled Exception: PlatformException(VideoError, Video player had error com.google.android.exoplayer2.ExoPlaybackException: Source error, null, null)
» 下一篇: [Flutter]Unhandled Exception: PlatformException(VideoError, Video player had error com.google.android.exoplayer2.ExoPlaybackException: Source error, null, null)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
2021-02-19 Flutter/Dart疫情助手