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

Flutter新版本报错:Object?无法分配给String、期望Widget却得到List

问题修复方案

这两个报错都是Dart 2.12+ 引入空安全和严格类型校验后出现的旧代码兼容性问题,修复方法如下:


报错1:期望得到Widget类型的值,却得到了List类型的值

原因

Column的children参数要求传入扁平化的Widget数组,你直接将map生成的List<Answer>作为元素放在children数组里,相当于数组嵌套了另一层数组,不符合类型要求。

修复

在map生成的List前添加展开运算符...,把List内的Widget平铺到children数组中。


报错2:参数类型'Object?'不能分配给参数类型'String'

原因

你定义的question数组的Map值类型为Object,Dart严格类型校验下,从Map中取出的值会被推断为Object?类型,不能直接传入要求String类型参数的Question、Answer组件。

修复

对取出的值显式做类型转换,确认是String类型后再传入组件。


修复后完整代码

final List<Map<String, Object>> question = [
    {
      'questionText': 'what\'s your favorite\'s color?',
      'answers': [
        'Black',
        'Green',
        'Blue',
        'Yellow',
      ]
    },
    {
      'questionText': 'Select a true fact about Paulo Maldini!',
      'answers': [
        'He is dead',
        'He is alive',
        'He killed',
        'He is single',
      ]
    },
  ];

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
          appBar: AppBar(
            centerTitle: true,
            title: MyText("Quiz Bahlol", fontstyle2),
          ),
          body: Container(
            width: double.infinity,
            child: Column(
              children: <Widget>[
                // 对取出的questionText显式转型为String
                Question(question[_questionIndex]['questionText'] as String),
                // 加展开运算符,同时把answers转型为List<String>
                ...(question[_questionIndex]['answers'] as List<String>).map((answer) {
                  return Answer(answerQuestion, answer);
                }).toList(),
              ],
            ),
          )),
    );

可选优化方案

如果不想每次取值都做类型转换,可以直接修改question的定义,把Map的value类型声明为dynamic,修改后只需要添加展开运算符就可以正常运行,无需额外做类型转换:

final List<Map<String, dynamic>> question = [
  // 原有内部内容保持不变
];

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 13:09:03