Iterating through a list of items with each step awaiting user input before moving on to next item in list
Solution 1:
One solution is to use two lists. A source list with all the questions, and a second list to display the questions as they are answered.
Here is your code updated with a very basic solution as example.
Note I added in a small boolean check so an already answered question can't be answered twice, and also to stop throwing an error once all questions are completed.
import 'package:flutter/material.dart';
class QuestionScreen extends StatefulWidget {
QuestionScreen();
@override
_QuestionScreenState createState() => _QuestionScreenState();
}
class _QuestionScreenState extends State<QuestionScreen> {
List<Question> listOfQuestions = [Question(), Question(), Question()];
List<Question> listOfQuestionsToDisplay = [];
int currentIndex = 0;
initState() {
listOfQuestionsToDisplay.add(listOfQuestions[0]);
super.initState();
}
onQuestionPress({required int index}) {
print('index pressed is $index');
print('current index is $currentIndex');
if (index < currentIndex) {
print('already pressed');
} else if (listOfQuestions.length == listOfQuestionsToDisplay.length) {
print('all questions answered');
} else {
listOfQuestionsToDisplay.add(listOfQuestions[index + 1]);
currentIndex++;
setState(() {});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
Text('List Of Questions'),
...listOfQuestionsToDisplay.map((eachQuestion) {
return Card(
elevation: 10,
margin: EdgeInsets.symmetric(
vertical: 5,
horizontal: 10,
),
child: ListTile(
title: Text(
'${eachQuestion.questionText} Q/NO: ${listOfQuestionsToDisplay.indexOf(eachQuestion)}'),
subtitle: Row(
children: [
...eachQuestion.listOfOptionsForTheUserToSelect
.map((eachOption) {
return ElevatedButton(
onPressed: () => {
onQuestionPress(
index: listOfQuestionsToDisplay
.indexOf(eachQuestion)),
},
child: Text(eachOption),
);
}).toList()
],
),
),
);
}).toList()
],
),
);
}
}
class Question {
String questionText = "question";
List<String> listOfOptionsForTheUserToSelect = ["ans1", "ans2"];
}