Flutter:利用Future发送网络请求

张裕  论坛元老 | 2024-11-14 08:42:24 | 显示全部楼层 | 阅读模式
打印 上一主题 下一主题

主题 1404|帖子 1404|积分 4212

pubspec.yaml设置http的SDK
  1. cupertino_icons: ^1.0.8
  2. http: ^1.2.2
复制代码
  请求数据的格式转换
  1. // Map 转 json
  2. final chat = {
  3.   'name': '张三',
  4.   'message': '吃饭了吗',
  5. };
  6. final chatJson = json.encode(chat);
  7. print(chatJson);
  8. // json转Map
  9. final newChat = json.decode(chatJson);
  10. print(newChat);
复制代码
  发送请求
  1. import 'dart:convert'; // json依赖
  2. import 'package:flutter/material.dart';
  3. import 'package:http/http.dart' as http; // http请求依赖
  4. class Chat {
  5.   final String? name;
  6.   final String? message;
  7.   final String? imageUrl;
  8.   Chat({this.name, this.message, this.imageUrl});
  9.   //
  10.   factory Chat.formMap(Map map) {
  11.     return Chat(
  12.       name: map['name'],
  13.       message: map['message'],
  14.       imageUrl: map['imageUrl'],
  15.     );
  16.   }
  17. }
  18. class ChatPage extends StatefulWidget {
  19.   @override
  20.   State<ChatPage> createState() => _ChatPageState();
  21. }
  22. class _ChatPageState extends State<ChatPage> {
  23.   @override
  24.   void initState() {
  25.     super.initState();
  26.     getDatas().then((value) {
  27.    
  28.     }).catchError((onError) {
  29.       
  30.     }).whenComplete(() {
  31.       print('数据加载完毕');
  32.     }).timeout(Duration(seconds: 1)).catchError((err) {
  33.       print('超时时长1秒,提示请求超时');
  34.     });
  35.   }
  36. }
  37. // async:异步的请求,不用卡在这等待
  38. Future<List> getDatas() async {
  39.   final url =
  40.       Uri.parse('http://rap2api.taobao.org/app/mock/321326/api/chat/list');
  41.   final res = await http.get(url);
  42.   if (res.statusCode == 200) {
  43.     // 获取相应数据,转成Map类型
  44.     final resBody = json.decode(res.body);
  45.     // map遍历chat_list,把每一项item转成模型数据,最后转成List
  46.     List chatList =
  47.         resBody['chat_list'].map((item) => Chat.formMap(item)).toList();
  48.     return chatList;
  49.   } else {
  50.     throw Exception('statusCode:${res.statusCode}');
  51.   }
  52. }
复制代码
  FutureBuilder 发送的请求
  1. return Scaffold(
  2.   body: Container(
  3.   child: FutureBuilder(
  4.       future: getDatas(),
  5.       builder: (BuildContext context, AsyncSnapshot snapshot) {
  6.         print('data:${snapshot.data}');
  7.         if (snapshot.connectionState == ConnectionState.waiting) {
  8.           return const Center(
  9.             child: Text('Loading...'),
  10.           );
  11.         }
  12.         return ListView(
  13.           children: snapshot.data.map<Widget>((item) {
  14.             return ListTile(
  15.                 title: Text(item.name),
  16.                 subtitle: Container(
  17.                   alignment: Alignment.bottomCenter,
  18.                   height: 25,
  19.                   child: Text(
  20.                     item.message,
  21.                     overflow: TextOverflow.ellipsis,
  22.                   ),
  23.                 ),
  24.                 leading: Container(
  25.                   width: 44,
  26.                   height: 44,
  27.                   decoration: BoxDecoration(
  28.                       borderRadius: BorderRadius.circular(6.0),
  29.                       image: DecorationImage(
  30.                           image: NetworkImage(item.imageUrl))),
  31.                 ));
  32.           }).toList(),
  33.         );
  34.       }),
  35.   )
  36. );
复制代码

   声明变量接收接口数据,在页面中利用该变量去渲染页面的方式
  1. class _ChatPageState extends State<ChatPage> {
  2.   List _datas = [];
  3.   @override
  4.   void initState() {
  5.     super.initState();
  6.     getDatas().then((value) {
  7.       setState(() {
  8.         _datas = value;
  9.       });
  10.     }).catchError((onError) {
  11.    
  12.         });
  13.   }
  14. }
  15. body: Container(
  16.   child: Container(
  17.     child: _datas.length == 0 ? Center(child: Text('Loading...')) :
  18.     ListView.builder(
  19.       itemCount: _datas.length,
  20.       itemBuilder: (BuildContext context, int index) {
  21.         return ListTile(
  22.             title: Text(_datas[index].name),
  23.             subtitle: Container(
  24.               alignment: Alignment.bottomCenter,
  25.               height: 25,
  26.               child: Text(
  27.                 _datas[index].message,
  28.                 overflow: TextOverflow.ellipsis,
  29.               ),
  30.             ),
  31.             leading: Container(
  32.               width: 44,
  33.               height: 44,
  34.               decoration: BoxDecoration(
  35.                 borderRadius: BorderRadius.circular(6.0),
  36.                 image: DecorationImage(image: NetworkImage(_datas[index].imageUrl))
  37.               ),
  38.             )
  39.         );
  40.       },
  41.     )
  42.   )
  43. )
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

张裕

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表