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

Flutter动态加载多选项Widget报错:期望List类型却得到List类型

解决Flutter类型错误:Expected a value of type 'List', but got one of type List

这个错误本质是Dart类型推断失效导致的:虽然你调试确认jsonDecode返回的是List,但返回值默认是dynamic类型,编译器无法确定它具体是Column.children需要的可迭代类型,从而抛出类型不匹配的错误。

修复方案

给options变量加上显式类型转换,明确它的List类型,让编译器能正确推断后续map操作的返回类型:

Widget _answerField(BuildContext context) {
    var state = Provider.of<EnrolmentDetailState>(context);

    if (widget.question.type == QuestionType.truefalse.value ||
        widget.question.type == QuestionType.multiplechoice.value) {
      // 显式转换为List<String>(如果选项都是字符串),或者List<dynamic>兼容更多类型
      final List<String> options = jsonDecode(jsonDecode(widget.question.answer_options!)) as List<String>;
      return Flexible(
          flex: 3,
          child: Container(
            padding: const EdgeInsets.all(20),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: options.map((opt) {
                return Container(
                  height: 90,
                  margin: const EdgeInsets.only(bottom: 10),
                  color: Colors.black26,
                  child: InkWell(
                    onTap: () {
                      state.selected = opt;
                      response.answer_options = opt;
                    },
                    child: Container(
                      padding: const EdgeInsets.all(16),
                      child: Row(
                        children: [
                          state.selected == opt 
                              ? const Icon(Icons.check_circle_rounded, size: 30) 
                              : const Icon(Icons.radio_button_unchecked, size: 30),
                          Expanded(
                            child: Container(
                              margin: const EdgeInsets.only(left: 16),
                              child: Text(
                                opt,
                                style: Theme.of(context).textTheme.bodyText2,
                              ),
                            ),
                          )
                        ],
                      ),
                    ),
                  ),
                );
              }).toList(),
            ),
          ));
    }
    // 补充else分支返回值,避免编译报错
    return const SizedBox();
}

额外优化建议

为了代码更健壮,可以先判断转换后的类型是否合法,避免强制转换失败:

final decoded = jsonDecode(jsonDecode(widget.question.answer_options!));
if (decoded is List) {
  final List<String> options = decoded.cast<String>();
  // 后续渲染逻辑
} else {
  // 处理非List的异常情况,比如返回错误提示
  return const Text("选项格式错误");
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 21:37:35