从 dart 访问 json 中的数组值元素
Access to a element of array value in json from dart
我在 flutter 中有这个 const 变量:
static const questions = [
{
"question": "question",
"answers": ["1", "2"],
"message":
"message",
},
]
如何从 dart 访问“1”?
我尝试使用 QuestionContent.questions[0]["answers"][0].
但是我得到了错误 "The method '[]' can't be unconditionally invoked because the receiver can be 'null'"
尝试使用:
Text((QuestionContent.questions[0] as Map<String, dynamic>)['answers'][0] ?? '')
或:
Text((questions[0]['answers'] as List<String>)[0]),
试试下面的代码:
const questions = [
{
"question": "question",
"answers": ["1", "2"],
"message":
"message",
},
];
Map<String, Object> question = questions[0];
List<String> answers = question["answers"] as List<String>;
String firstAnswer = answers.elementAt(0);
您收到错误的原因是编译器无法判断您的 QuestionContent.questions[0]["answers"]
是否为空:
我在 flutter 中有这个 const 变量:
static const questions = [
{
"question": "question",
"answers": ["1", "2"],
"message":
"message",
},
]
如何从 dart 访问“1”?
我尝试使用 QuestionContent.questions[0]["answers"][0].
但是我得到了错误 "The method '[]' can't be unconditionally invoked because the receiver can be 'null'"
尝试使用:
Text((QuestionContent.questions[0] as Map<String, dynamic>)['answers'][0] ?? '')
或:
Text((questions[0]['answers'] as List<String>)[0]),
试试下面的代码:
const questions = [
{
"question": "question",
"answers": ["1", "2"],
"message":
"message",
},
];
Map<String, Object> question = questions[0];
List<String> answers = question["answers"] as List<String>;
String firstAnswer = answers.elementAt(0);
您收到错误的原因是编译器无法判断您的 QuestionContent.questions[0]["answers"]
是否为空: