专业的编程技术博客社区

网站首页 > 博客文章 正文

二、Flutter网络请求数据(flutter connectivity)

baijin 2024-08-11 13:40:16 博客文章 17 ℃ 0 评论

目录

一、集成dio

二、ListView

三、请求网络数据

四、刷新ListView

五、flutter run

一、集成dio

dio: ^2.1.10是一个强大的Dart Http请求库,支持Restful API、FormData、拦截器、请求取消、Cookie管理、文件上传/下载、超时、自定义适配器。

pubspec.yaml 中 添加dio: ^2.1.10,并同步 packages get。

在相应的 .dart 文件中添加引用 import 'package:dio/dio.dart'。

dependencies:
 flutter:
 sdk: flutter
 # The following adds the Cupertino Icons font to your application.
 # Use with the CupertinoIcons class for iOS style icons.
 cupertino_icons: ^0.1.2
 dio: ^2.1.10

二、ListView

ListView是最常用的滑动组件。它在滚动方向上一个接一个地显示它的孩子。在交叉轴中,需要孩子填充ListView。

@override
 Widget build(BuildContext context) {
 return Scaffold(
 appBar: AppBar(
 title: Text('网络请求数据'),
 ),
 body: Center(
 child: ListView.builder(
 itemCount: listData == null ? 0 : listData.length,
 itemBuilder: this._getItems)),
 );
 }

三、请求网络数据

进入页面时系统会自动调用 initState(),为了保证第一次正常加载,这个时候调用_loadData();

void _loadData() async {
 var result = await YFHttp.request('/v2/movie/in_theaters',
 data: {
 'apikey': "0b2bdeda43b5688921839c8ecb20399b",
 },
 method: YFHttp.GET);
 }

四、刷新ListView

网络请求是异步的造成数据不能同步到ListView,这个时候就需要刷新表格,把网络数据加载到ListView里面。

 setState(() {
 listData = result['subjects'];
 });

五、flutter run

终于一切都准备好了,只差flutter run。



Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表