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

Flutter浏览器报错:期望List<Dynamic>类型,实际获取Null

解决Flutter中“Expected a value of type 'List',but got one of type 'Null'”错误

问题根源

  • build方法中调用setasset():build会在组件状态变化时多次执行,每次调用setasset()会修改assettoload的值,导致FutureBuilder的future不断重新创建,加载流程混乱,甚至可能出现数据还没加载完成就切换资源的情况。
  • 未处理FutureBuilder的快照状态:直接访问snapshot.data并调用toString(),当快照处于加载中(connectionState == ConnectionState.waiting)或加载失败时,snapshot.data为null,jsonDecode("null")返回null,而你将其赋值给非可空的List mydata,触发类型不匹配错误。
  • 缺乏类型检查与空安全处理:没有验证jsonDecode的结果是否为List类型,也没有处理结果为null的情况,直接强制赋值给List变量。

修复步骤

  1. 将setasset()移至initState
    把初始化assettoload的逻辑放到initState中,确保只执行一次,避免build重复触发资源切换:

    @override
    void initState() {
      super.initState();
      setasset(); // 仅在组件初始化时执行一次
    }
    
  2. 完善FutureBuilder的快照状态处理
    在builder中先判断快照的连接状态和数据有效性,再进行JSON解析和类型检查:

    Widget build(BuildContext context) {
      return FutureBuilder(
        future: DefaultAssetBundle.of(context).loadString(assettoload, cache: false),
        builder: (context, snapshot) {
          // 处理加载中状态
          if (snapshot.connectionState == ConnectionState.waiting) {
            return const Scaffold(
              body: Center(child: Text("Loading")),
            );
          }
    
          // 处理加载错误
          if (snapshot.hasError) {
            return Scaffold(
              body: Center(child: Text("加载失败: ${snapshot.error}")),
            );
          }
    
          // 检查数据是否为空
          if (snapshot.data == null) {
            return const Scaffold(
              body: Center(child: Text("无数据")),
            );
          }
    
          // 解析JSON并检查类型
          final decodedData = jsonDecode(snapshot.data!);
          if (decodedData is List) {
            return quizpage(mydata: decodedData);
          } else {
            // JSON不是List类型的情况
            return const Scaffold(
              body: Center(child: Text("JSON格式错误,预期为数组")),
            );
          }
        },
      );
    }
    
  3. 确保JSON文件格式正确
    检查你的JSON文件是否确实是数组格式(比如[{"key": "value"}, ...]),如果是对象格式({"key": "value"}),jsonDecode会返回Map,也会触发类型不匹配错误,需要对应调整代码或JSON文件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 04:01:06