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

Flutter开发:列表映射Widget时遭遇Null类型错误的技术求助

Fixing the "Expected List, got Null" TypeError in Your Flutter Anime Demo

Hey there! Let's break down why you're seeing that frustrating TypeErrorImpl and fix it quickly.

The Root Cause

Looking at your questions list in main.dart, there's a tiny typo that's causing all the trouble:

  • The first question uses the key 'answersText' (note the plural "answers")
  • Every other question uses 'answerText' (singular "answer")

When your app tries to build the first question (qIndex = 0), you're trying to access questions[qIndex]['answerText']—but that key doesn't exist in the first map! So it returns null, and when you try to cast that null to a List<String>, Flutter throws the error you're seeing.

Quick Fix

Just correct the key in the first question to match the rest:

{
 'questionText': 'which anime do you prefer',
 'answerText': [ // Changed from 'answersText' to 'answerText'
  'Naruto',
  'One Punch Man',
  'my hero acadamea',
  'one piece',
  'death note',
  'Attack on titan',
 ]
},

Bonus: Add Null Safety to Prevent Future Bugs

To avoid similar crashes if you ever make a typo again, add a null check before mapping the answers. Modify your body column code like this:

body: Column(
 children: [
  question(questions[qIndex]['questionText'].toString()),
  ...(questions[qIndex]['answerText'] as List<String>?)?.map((answer) {
   return Answer(questionanswered, answer);
  }).toList() ?? [] // If answerText is null, return an empty list instead of crashing
 ],
),

This way, even if a key is missing, your app won't crash—it just won't show any answers for that question, which is easier to debug than a full crash.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 03:24:08