Flutter报错:List<Object>无法强转为List<String>类型异常
Flutter运行时List类型强转错误修复
错误信息
运行时抛出类型转换异常:type 'List<Object>' is not a subtype of type 'List<String>' in type cast
调试控制台指向错误触发组件为Quiz,定位到出错代码段为:
...(questions[question_index]['Answers'] as List<String>).map((answer) { return Answers(answerquestions, answer); }).toList()
附原Quiz组件实现:
class Quiz extends StatelessWidget { final List<Map<String, dynamic>> questions; final int question_index; final void Function() answerquestions; Quiz( {required this.questions, required this.answerquestions, required this.question_index}); @override Widget build(BuildContext context) { return (Column( children: [ Question(questions[question_index]['QuestionText'] as String), ...(questions[question_index]['Answers'] as List<String>).map((answer) { return Answers(answerquestions, answer); }).toList() ], )); } }
错误原因
- 你的
questions列表类型为List<Map<String, dynamic>>,当你从中取出Answers字段时,Dart运行时识别到的实际列表类型是List<Object> - Dart不支持直接将
List<父类型>通过as关键字强转为List<子类型>,直接强转List<String>就会触发类型不匹配错误
修复方案
你可以任选以下一种方式修复:
- 使用
cast<String>()做安全类型转换
不要直接强转整个列表,先将取出的内容转为通用List,再调用cast方法指定子类型:...(questions[question_index]['Answers'] as List).cast<String>().map((answer) { return Answers(answerquestions, answer); }).toList() - 逐元素转换为String类型
遍历列表时将每个元素显式转为String,兼容性最强,即使列表里混入非String类型的内容也不会报错:...(questions[question_index]['Answers'] as List).map((answer) { return Answers(answerquestions, answer.toString()); }).toList() - 数据源层面显式声明类型(根源规避)
在初始化questions列表时,显式给Answers字段指定泛型为List<String>,避免Dart自动推断为List<Object>:// 初始化questions示例 const questions = [ { 'QuestionText': '第一个问题?', 'Answers': <String>['选项A', '选项B', '选项C'], // 显式声明List泛型为String } ];
注意:只要是从
dynamic类型的Map中取列表值,都不建议直接用as List<具体类型>强转,很容易因为类型推断不符合预期触发运行时错误。
内容的提问来源于stack exchange,提问作者Josua Hero Hutabarat
相关产品推荐
相关产品推荐

