如何解决Dart中“参数类型Object?不能分配给参数类型String”报错
问题原因
- 字段名大小写不匹配:定义的答案分数字段为小写
score,代码取值时写为大写Score,字段不匹配会导致取值为空 - 类型未明确转换:你将answers的Map泛型声明为
Map<String, Object>,从Map中取出的值默认是Object?可空对象类型,无法直接赋值给要求String类型的参数
解决方案
快速修复
先修正字段大小写,再对取出的值做显式类型转换,修改后的代码如下:
Question(question[questionindex]['questionText'] as String), ...(question[questionindex]['answers'] as List<Map<String,Object>>).map((answer) { return Answer(() => answerQuestion(answer['score'] as String), answer['text'] as String); }).toList(),
如果要兼容空值避免运行时报错,可以增加空安全 fallback 逻辑:
Question(question[questionindex]['questionText'] ?? '默认问题'), ...(question[questionindex]['answers'] as List<Map<String,Object>>).map((answer) { final score = answer['score'] as String? ?? '0'; final text = answer['text'] as String? ?? '默认选项'; return Answer(() => answerQuestion(score), text); }).toList(),
规范优化方案
推荐为数据定义实体类,从根源避免类型匹配问题,代码可维护性更高:
// 定义实体类 class QuestionItem { final String questionText; final List<AnswerItem> answers; QuestionItem({required this.questionText, required this.answers}); } class AnswerItem { final String text; final String score; AnswerItem({required this.text, required this.score}); } // 初始化数据 final _question = [ QuestionItem( questionText: "what's your favourite color?", answers: [ AnswerItem(text: 'Black', score: '10'), AnswerItem(text: 'Green', score: '80'), AnswerItem(text: 'Blue', score: '147'), AnswerItem(text: 'Yellow', score: '60'), ], ), QuestionItem( questionText: "what's your favourite animal?", answers: [ AnswerItem(text: 'Rabbit', score: '10'), AnswerItem(text: 'Tiger', score: '10'), AnswerItem(text: 'Elephant', score: '10'), AnswerItem(text: 'Lion', score: '10'), ], ), ]; // 调用代码,无需类型转换 Question(_question[questionindex].questionText), ..._question[questionindex].answers.map((answer) { return Answer(() => answerQuestion(answer.score), answer.text); }).toList(),
内容的提问来源于stack exchange,提问作者ingmbk
相关产品推荐
相关产品推荐

