Flutter中如何从Maps数组获取questionText及answers值并解决类型报错
报错原因
该报错是Dart类型系统的正常提示。你使用var定义questions数组时,Dart会自动推断数组元素的类型为Map<String, Object?>——因为每个Map内的value存在两种类型:String类型的questionText、Listanswers,所以Dart会将value统一向上推断为公共父类型Object?,直接取出的Object?类型值无法直接赋值给String类型的变量,就会触发该报错。
解决方法
- 方案1:定义数组时明确指定Map的value类型为dynamic,跳过编译时类型检查
修改数组定义为:
List<Map<String, dynamic>> questions = [ { 'questionText': 'What\'s your favorite color?', 'answers': ['Black', 'Red', 'Green', 'White'], }, { 'questionText': 'What\'s your favorite animal?', 'answers': ['Rabbit', 'Snake', 'Elephant', 'Lion'], }, { 'questionText': 'Who\'s your favorite instructor?', 'answers': ['Max', 'Max', 'Max', 'Max'], }, ];
修改完成后你原本的两种取值写法即可正常运行。
- 方案2:取值时做显式类型转换,无需修改原数组定义
将你的取值写法调整为:
// 取问题文本 questions.elementAt(1)['questionText'] as String; questions[_questionIndex]['questionText'] as String; // 取答案列表同理 questions[_questionIndex]['answers'] as List<String>;
- 方案3:安全校验写法,避免强转失败导致运行时崩溃
final currentQuestion = questions[_questionIndex]; final String questionText = currentQuestion['questionText'] is String ? currentQuestion['questionText'] as String : '无有效问题'; final List<String> answers = currentQuestion['answers'] is List<String> ? currentQuestion['answers'] as List<String> : [];
内容的提问来源于stack exchange,提问作者Soheil
相关产品推荐
相关产品推荐

