Mohamadamin
Mohamadamin

Reputation: 617

Access to a element of array value in json from dart

I have this const variable in flutter:

static const questions = [
    {
      "question": "question",
      "answers": ["1", "2"],
      "message":
          "message",
    }, 
]

how to access to "1" from dart??

I try using QuestionContent.questions[0]["answers"][0]. But I got error "The method '[]' can't be unconditionally invoked because the receiver can be 'null'"

Upvotes: 0

Views: 69

Answers (2)

聂超群
聂超群

Reputation: 2120

Try code below:

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);

The reason you get the error is the compiler could not tell whether your QuestionContent.questions[0]["answers"] is null or not:

enter image description here

Upvotes: 1

Xuuan Thuc
Xuuan Thuc

Reputation: 2521

Try use:

Text((QuestionContent.questions[0] as Map<String, dynamic>)['answers'][0] ?? '')

or:

Text((questions[0]['answers'] as List<String>)[0]),

Upvotes: 1

Related Questions