Home > Enterprise >  The method 'data' can't be unconditionally invoked because the receiver can be '
The method 'data' can't be unconditionally invoked because the receiver can be '

Time:10-15

questionModel.question = questionSnapshot.data()["question"];

// The method 'data' can't be unconditionally invoked because the receiver can be 'null'. Try making the call conditional (using '?.')

/// shuffling the options
List<String> options = [
  questionSnapshot.data()["option1"],
  questionSnapshot.data()["option2"],
  questionSnapshot.data()["option3"],
  questionSnapshot.data()["option4"]
];
options.shuffle();

questionModel.option1 = options[0];
questionModel.option2 = options[1];
questionModel.option3 = options[2];
questionModel.option4 = options[3];
questionModel.correctAnswer = questionSnapshot.data()["correctAnswer"];
questionModel.answered = false;

CodePudding user response:

As the error message says, calling questionSnapshot.data() can return null and you can't call further operations on that.

You'll want to check if the data() method returns null before processing the questions, for example with:

var data = questionSnapshot.data();
if (data != null) {
  List<String> options = [
    data["option1"],
    data["option2"],
    data["option3"],
    data["option4"]
  ];
  options.shuffle();
  ...
  • Related