Flutter开发:列表映射Widget时遭遇Null类型错误的技术求助
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

