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

Dart中Map列表赋值时出现‘Object?’无法分配给‘int’/‘String’参数类型的错误排查求助

问题分析与解决方案

Hey there! Let's fix your issues one by one:

1. 错误的集合类型定义(核心问题)

Looking at your questions list, you made a critical mistake with the answer field in the second and third map entries:

  • For "Questão 1", you correctly used square brackets [] to define a List of answer maps
  • But for "Questão 2" and "Questão 3", you used curly brackets {}, which in Dart defines a Set (not a List). Not only does this mismatch the type you're trying to cast to later, but defining a Set of maps like this is also invalid syntax (since maps aren't automatically hashable in this context).

First, fix the questions list by replacing the curly brackets for answer with square brackets:

var questions = [
  {
    'questiontext': "Questão 1",
    'answer': [
      {'text': 'Black', 'score': 10},
      {'text': 'Red', 'score': 5},
      {'text': 'Green', 'score': 3},
      {'text': 'White', 'score': 1},
    ]
  },
  {
    'questiontext': "Questão 2",
    'answer': [  // Changed from {} to []
      {'text': 'Rabbit', 'score': 3},
      {'text': 'Snake', 'score': 11},
      {'text': 'Elephant', 'score': 5},
      {'text': 'Lion', 'score': 9},
    ],
  },
  {
    'questiontext': "Questão 3",
    'answer': [  // Changed from {} to []
      {'text': 'Peter', 'score': 1},
      {'text': 'Paul', 'score': 1},
      {'text': 'Max', 'score': 1},
    ],
  }
];

2. 明确的类型转换

Even after fixing the list type, when you extract answer['text'] and answer['score'], Dart only knows they're of type Object? (since your map is Map<String, Object>). You need to explicitly cast them to String and int to match your Answer widget's parameter types.

Here's the corrected code snippet for building your answers:

final List<Map<String, Object>> questions;
...
(questions[0]['answer'] as List<Map<String, Object>>)
    .map((answer) {
  return Answer(
    () => textfunction(answer['score'] as int),  // Cast to int
    answer['text'] as String  // Cast to String
  );
}).toList()

Why using dynamic didn't work?

Switching to dynamic might suppress static analysis errors, but it doesn't fix the underlying issue: your initial answer fields were Sets instead of Lists. Even with dynamic, you'd run into runtime errors when trying to call map() on a Set. Fixing the collection type first is essential.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 11:17:47