Flutter中动态生成卡片展示HTTP请求未知数量返回数据
Flutter动态生成卡片展示HTTP请求结果解决方案
核心思路
用ListView.builder(或ListView.separated)实现按需渲染,它会根据HTTP返回的元素数量自动生成对应数量的卡片/容器,完美适配未知数量的请求结果。
分步实现
1. 定义数据模型
先把HTTP返回的JSON数据映射成Dart模型类,方便后续操作:
class ItemModel { final String id; final String title; final String content; ItemModel({required this.id, required this.title, required this.content}); // 从JSON解析成模型 factory ItemModel.fromJson(Map<String, dynamic> json) { return ItemModel( id: json['id'], title: json['title'], content: json['content'], ); } }
2. 发起HTTP请求并获取数据
在State类中维护一个列表变量存储请求结果,同时处理加载和错误状态:
class _MyPageState extends State<MyPage> { List<ItemModel> _items = []; bool _isLoading = true; String? _errorMessage; @override void initState() { super.initState(); _fetchData(); } Future<void> _fetchData() async { try { final response = await http.get(Uri.parse('你的接口地址')); if (response.statusCode == 200) { final List<dynamic> jsonList = json.decode(response.body); setState(() { _items = jsonList.map((json) => ItemModel.fromJson(json)).toList(); _isLoading = false; }); } else { throw Exception('请求失败,状态码:${response.statusCode}'); } } catch (e) { setState(() { _errorMessage = e.toString(); _isLoading = false; }); } }
3. 动态生成卡片/容器
用ListView.builder根据列表长度自动渲染元素:
@override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('动态卡片展示')), body: _buildBody(), ); } Widget _buildBody() { if (_isLoading) { return const Center(child: CircularProgressIndicator()); } if (_errorMessage != null) { return Center(child: Text('错误:$_errorMessage')); } return ListView.builder( padding: const EdgeInsets.all(16), // 元素数量就是请求返回的列表长度 itemCount: _items.length, // 为每个元素生成卡片 itemBuilder: (context, index) { final item = _items[index]; return Card( margin: const EdgeInsets.only(bottom: 12), child: Padding( padding: const EdgeInsets.all(16), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text(item.title, style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold)), const SizedBox(height: 8), Text(item.content), ], ), ), ); }, ); } }
关键说明
itemCount直接绑定_items.length,HTTP返回多少元素就生成多少卡片itemBuilder会为每个索引位置生成对应的卡片,按需创建,性能更优- 额外处理了加载中、错误状态,提升用户体验
内容的提问来源于stack exchange,提问作者Deenan Djigbenou
相关产品推荐
相关产品推荐

