我有一個要逐個呈現給用戶的專案串列,這是通過在顯示下一個專案之前等待用戶輸入來控制的。
舉一個背景關系示例,這可能是用戶必須一一回答的問題串列。每個問題都有問題主體和供用戶選擇的選項串列。它們可以由單個Card開始呈現,一旦他們選擇了其中一個選項,就會捕獲該值,下一個Card將顯示在下方
所以我所擁有的超級簡化版本是這樣的
import 'package:flutter/material.dart';
class QuestionScreen extends StatefulWidget {
QuestionScreen();
@override
_QuestionScreenState createState() => _QuestionScreenState();
}
class _QuestionScreenState extends State<QuestionScreen> {
@override
Widget build(BuildContext context) {
List<Question> listOfQuestions = [
new Question(),
new Question(),
new Question()
];
return Scaffold(
body: Column(
children: [
Text('List Of Questions'),
...listOfQuestions.map((eachQuestion) {
return Card(
elevation: 10,
margin: EdgeInsets.symmetric(
vertical: 5,
horizontal: 10,
),
child: ListTile(
title: Text(eachQuestion.questionText),
subtitle: Row(
children: [
...eachQuestion.listOfOptionsForTheUserToSelect
.map((eachOption) {
return ElevatedButton(
onPressed: () => {},
child: Text(eachOption),
);
}).toList()
],
),
),
);
}).toList()
],
),
);
}
}
class Question {
String questionText = "question";
List<String> listOfOptionsForTheUserToSelect = ["ans1", "ans2"];
}

uj5u.com熱心網友回復:
一種解決方案是使用兩個串列。包含所有問題的源串列,以及在回答問題時顯示問題的第二個串列。
這是您的代碼,以非常基本的解決方案為例進行了更新。
請注意,我添加了一個小的布爾檢查,因此無法回答兩次已回答的問題,并且在完成所有問題后也停止拋出錯誤。
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"];
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/410656.html
標籤:
上一篇:顫振集團登錄
