You need to enable JavaScript to run this app. Flutter开发中无法将Map类型JSON转换并渲染为ListView的问题
优惠活动
大模型
产品
解决方案
定价
更多

Flutter开发中无法将Map类型JSON转换并渲染为ListView的问题

接口数据渲染异常修复方案

核心问题定位

  • 变量作用域遮蔽问题:类层级定义的成员变量List items,在setState内部被重新通过Map items = json.decode(...)声明为局部变量。这个局部变量仅在setState的代码块内有效,类成员的items全程保持初始null状态,导致itemCount始终取0,页面自然没有内容渲染。你能通过print成功打印数据,就是因为print打印的是这个局部Map变量,接口请求本身是拿到数据了的。
  • 数据结构不匹配:接口返回的JSON是Map键值对结构,并非可以直接通过数字下标遍历的List,就算把局部变量正确赋值给类成员,直接拿Map计算长度、按下标取内容也无法完成渲染。
  • SDK适配问题:新版http包的get方法不支持直接传入字符串格式的URL,需要通过Uri.parse()解析后传入,否则会直接触发运行时异常。

具体修改操作

  • 删掉setState内部重复声明的局部items变量,把接口解码后的有效数据正确赋值给类层级的成员变量。
  • 从返回的大Map中找到嵌套的商品列表字段,将该Map结构的value集合转换为可遍历的List,适配ListView的渲染要求。
  • 补充加载状态标识与异常捕获逻辑,避免接口请求过程中页面白屏、无反馈。

修复后的可运行代码

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:async';
import 'dart:convert';

class HomePage extends StatefulWidget {
  @override
  HomePageState createState() => HomePageState();
}

class HomePageState extends State<HomePage> {
  List items = [];
  bool isLoading = true;

  Future<void> getData() async {
    try {
      final response = await http.get(
        Uri.parse('https://api.torn.com/torn/?selections=items&key=7PnSA9HkVB5B6eAK')
      );
      
      if (response.statusCode == 200) {
        final decodedRes = json.decode(response.body);
        // 从返回的大Map中取出嵌套的items字段,转为List供ListView使用
        final itemsMap = decodedRes['items'] as Map;
        setState(() {
          items = itemsMap.values.toList();
          isLoading = false;
        });
      }
    } catch (e) {
      setState(() {
        isLoading = false;
      });
      // 打印异常信息方便排查
      print('请求异常:$e');
    }
  }

  @override
  void initState() {
    super.initState();
    getData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: isLoading 
        ? const Center(child: CircularProgressIndicator())
        : ListView.builder(
            itemCount: items.length,
            itemBuilder: (context, index) {
              final currentItem = items[index];
              return Card(
                child: ListTile(
                  title: Text(currentItem['name'] ?? '暂无名称'),
                ),
              );
            },
          ),
    );
  }
}

内容的提问来源于stack exchange,提问作者StalowyJez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.16 07:36:04