You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter类型转换错误:Null无法转为List<dynamic>,图片加载失败

问题解决:type 'Null' is not a subtype of type 'List' in type cast

错误原因

你的JSON结构中,image并非顶层键,而是嵌套在data[0].data数组的每个子对象里。直接通过json.decode(jsongambar)["image"]取值会返回null,强制转换为List<dynamic>就触发了类型错误。另外代码里的rootBundle.rootBundle是冗余写法,会导致加载资源的额外问题。

修正步骤

  1. 修复_listKomik方法的路径取值
    调整代码,正确遍历JSON的嵌套结构,获取包含judul和image的漫画列表:

    Future<List<KomikModel>> _listKomik() async {
      // 移除冗余的rootBundle,直接调用loadString
      final jsongambar = await rootBundle.loadString('assets/datakomik.json');
      // 先取顶层的data数组
      final rootData = json.decode(jsongambar)["data"] as List<dynamic>;
      // 取第一个分类下的漫画数据列表
      final comicList = rootData.first["data"] as List<dynamic>;
      // 转换为KomikModel列表返回
      return comicList.map((e) => KomikModel.fromJson(e)).toList();
    }
    
  2. 确认KomikModel的解析逻辑正确
    确保你的模型类能正确从JSON对象中提取judul和image字段:

    class KomikModel {
      final String judul;
      final String image;
    
      KomikModel({required this.judul, required this.image});
    
      factory KomikModel.fromJson(Map<String, dynamic> json) {
        return KomikModel(
          judul: json["judul"] as String,
          image: json["image"] as String,
        );
      }
    }
    
  3. 完善FutureBuilder的UI渲染
    在builder中处理不同状态,并渲染漫画列表:

    FutureBuilder<List<KomikModel>>(
      future: _listKomik(),
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return const Center(child: CircularProgressIndicator());
        }
        if (snapshot.hasError) {
          return Center(child: Text('加载失败: ${snapshot.error}'));
        }
        if (!snapshot.hasData || snapshot.data!.isEmpty) {
          return const Center(child: Text('暂无漫画数据'));
        }
        return ListView.builder(
          itemCount: snapshot.data!.length,
          itemBuilder: (context, index) {
            final komik = snapshot.data![index];
            return ListTile(
              title: Text(komik.judul),
              leading: Image.asset(komik.image),
            );
          },
        );
      },
    )
    
  4. 检查pubspec.yaml的资源配置
    确保你的图片资源已在pubspec.yaml中注册,否则无法加载本地图片:

    flutter:
      assets:
        - images/
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 03:45:39