'Displaying multiple buttons from a list of questions with multiple options
so I'm trying to display a list of questions with options. A question may have 2 or 3 options. I want to display 3 options from the list.. and I only want it to be displayed if the question has 3 options.
final questionData = <Question>[
Question(
questionText: "You like to work with numbers",
option1: "Yes",
option2: "No"),
Question(
questionText: "Do you love reading poems, history and comics?.",
option1: "Yes",
option2: "No",
option3: "Sometimes"),
Question(
questionText: "You enjoy building things and working with your hands?",
option1: "Yes",
option2: "No"),
And this is my question model class
class Question {
String? questionText;
String? option1;
String? option2;
String? option3;
String? option4;
String? option5;
// constructor
Question(
{this.questionText,
this.option1,
this.option2,
this.option3,
this.option4,
this.option5});
}
I tried this method, but I still have null being displayed to the screen
int _questionNumber = 0;
var option3 = false;
late List<Question> questions = questionData;
// Function
Widget condition() {
Widget widget;
switch (option3) {
case true:
widget = Text(
questions[_questionNumber].option3.toString(),
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
),
);
break;
case false:
widget = Container();
break;
default:
widget = Container();
}
// Finally returning a Widget
return widget;
}
// check if options are available
void isAvailable (){
if (questions[_questionNumber].option3.toString() != null){
option3 = true;
notifyListeners();
}
}
Solution 1:[1]
Inside of your isAvailable function you have the following statement:
questions[_questionNumber].option3.toString() != null
The only important part here is .toString() != null, which is always false. any String != null.
Your variable option3 is already defined as null-possibly String, you should probably just use
String? option3;
And I assume you can and you should just remove the .toString() part in your if statement
questions[_questionNumber].option3 != null
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Maksim Nikolaev |
