Flutter:为动态HTTP POST的JSON响应按索引实现类缓存功能
解决方案:按索引缓存API响应
这个需求完全可行!你当前代码的问题在于直接给空列表的索引赋值——Dart中初始化的空列表_myResponse长度为0,根本不存在[0]、[1]这类索引,直接赋值会触发RangeError。下面是调整后的完整实现方案:
关键改动点
- 维护一个记录当前存储位置的索引变量,点击按钮时自动递增
- 修复列表赋值逻辑,确保目标索引存在后再存入数据
修改后的完整代码示例
import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; class YourWidget extends StatefulWidget { const YourWidget({super.key}); @override State<YourWidget> createState() => _YourWidgetState(); } class _YourWidgetState extends State<YourWidget> { List<dynamic> _myResponse = []; int _currentIndex = 0; // 新增:记录下次要存入的索引位置 Future<void> trytoFetch(int myIndex, int parameter) async { var url = "https://jsonplaceholder.typicode.com/posts/$parameter"; Map<String, String> headers = { 'Content-type': 'application/json', 'Accept': 'application/json', }; try { final response = await http.post(url, headers: headers); final responseJson = json.decode(response.body); if (response.statusCode == 200) { setState(() { // 核心修复:确保列表长度足够容纳目标索引 // 如果目标索引超出当前列表长度,先填充空值占位 while (_myResponse.length <= myIndex) { _myResponse.add(null); } _myResponse[myIndex] = responseJson; }); } else { throw Exception('Failed to load data: ${response.statusCode}'); } } catch (e) { // 可以在这里添加错误提示逻辑,比如弹出Toast print('请求出错:$e'); } } @override Widget build(BuildContext context) { return Scaffold( body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ ElevatedButton( onPressed: () { // 示例:每次点击用当前索引+1作为请求参数(可根据你的需求调整) int requestParameter = _currentIndex + 1; // 传入当前要存储的索引和请求参数 trytoFetch(_currentIndex, requestParameter); // 递增索引,下次存到下一个位置 setState(() { _currentIndex++; }); }, child: const Text('发起请求'), ), // 测试用:打印指定索引的缓存数据 TextButton( onPressed: () { if (_myResponse.length > 0) print(_myResponse[0]); if (_myResponse.length > 1) print(_myResponse[1]); if (_myResponse.length > 2) print(_myResponse[2]); }, child: const Text('打印缓存数据'), ), ], ), ), ); } }
代码说明
- 索引维护:
_currentIndex变量记录下一次要存入数据的位置,点击按钮后自动递增,确保每次请求的结果按顺序存入_myResponse的对应索引位 - 列表安全赋值:通过
while循环检查列表长度,若目标索引超出当前列表长度,先填充null占位,避免直接访问不存在的索引报错 - 异常优化:新增
try-catch包裹整个请求逻辑,避免请求失败导致程序崩溃,同时方便你添加错误提示
这样修改后,你就能通过print(_myResponse[0])、print(_myResponse[1])等方式直接访问对应索引的缓存JSON数据了。
内容的提问来源于stack exchange,提问作者dustin333
相关产品推荐
相关产品推荐

