JuLearn/lib/learn.dart

114 lines
3.2 KiB
Dart
Raw Normal View History

2023-06-01 16:11:03 +02:00
import 'package:flutter/material.dart';
import 'package:ju_learn/main.dart';
class QuizPage extends StatefulWidget {
Vault v;
QuizPage(this.v, {super.key});
@override
_QuizPageState createState() => _QuizPageState(v);
}
class _QuizPageState extends State<QuizPage> {
int _currentQuestionIndex = 0;
int ask_state = -1;
int _score = 0;
Vault v;
_QuizPageState(this.v);
void _checkAnswer(int selectedIndex) {
//if (selectedIndex == v.questions[_currentQuestionIndex].correct) {
// setState(() {
// _score++;
// });
//}
setState(() {
ask_state = selectedIndex;
});
}
void _nextQuestion() {
setState(() {
if (_currentQuestionIndex < v.questions.length - 1) {
ask_state = -1;
_currentQuestionIndex++;
} else {
_showResultDialog();
}
});
}
void _showResultDialog() {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: const Text('Quiz Completed'),
content: Text('Your score: $_score / ${v.questions.length}'),
actions: [
TextButton(
child: const Text('Restart'),
onPressed: () {
setState(() {
_currentQuestionIndex = 0;
_score = 0;
});
Navigator.of(context).pop();
},
),
],
);
},
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Learn App'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(
v.questions[_currentQuestionIndex].quest,
style: const TextStyle(
fontSize: 20.0,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 20.0),
...v.questions[_currentQuestionIndex].answers.map(
(option) {
return Container(
margin: const EdgeInsets.symmetric(vertical: 8.0),
child: ElevatedButton(
onPressed: () => ask_state == -1
? _checkAnswer(
v.questions[_currentQuestionIndex].answers
.indexOf(option),
)
: _nextQuestion(),
child: Text(option),
style: ElevatedButton.styleFrom(
backgroundColor: ask_state == -1
? Colors.blue
: (v.questions[_currentQuestionIndex].correct ==
v.questions[_currentQuestionIndex].answers
.indexOf(option)
? Colors.green
: Colors.red), // Change the button color here
),
));
},
),
],
),
),
);
}
}