JuLearn/lib/learn.dart

125 lines
3.5 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
2023-06-01 16:38:20 +02:00
// ignore: no_logic_in_create_state, library_private_types_in_public_api
_QuizPageState createState() {
v.randomize();
return _QuizPageState(v);
}
2023-06-01 16:11:03 +02:00
}
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(
2023-06-01 16:45:42 +02:00
title: Text('Learning: ${v.name}'),
2023-06-01 16:11:03 +02:00
),
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),
2023-06-01 16:45:42 +02:00
child: FilledButton(
onPressed: () => ask_state == -1
? _checkAnswer(
v.questions[_currentQuestionIndex].answers
.indexOf(option),
)
: _nextQuestion(),
child: Text(option),
style: FilledButton.styleFrom(
2023-06-01 16:38:20 +02:00
backgroundColor: ask_state == -1
2023-06-01 16:45:42 +02:00
? null
2023-06-01 16:38:20 +02:00
: (v.questions[_currentQuestionIndex].correct ==
v.questions[_currentQuestionIndex].answers
.indexOf(option)
? Colors.green
: Colors.red),
2023-06-01 16:45:42 +02:00
)));
2023-06-01 16:11:03 +02:00
},
),
2023-06-01 16:38:20 +02:00
if (ask_state != -1)
Text(
v.questions[_currentQuestionIndex].explanation,
style: const TextStyle(
fontSize: 15.0,
fontWeight: FontWeight.bold,
),
)
2023-06-01 16:11:03 +02:00
],
),
),
);
}
}