import 'package:flutter/material.dart'; import 'package:ju_learn/main.dart'; class QuizPage extends StatefulWidget { Vault v; QuizPage(this.v, {super.key}); @override // ignore: no_logic_in_create_state, library_private_types_in_public_api _QuizPageState createState() { v.randomize(); return _QuizPageState(v); } } class _QuizPageState extends State { 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: Text('Learning: ${v.name}'), ), 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: FilledButton( onPressed: () => ask_state == -1 ? _checkAnswer( v.questions[_currentQuestionIndex].answers .indexOf(option), ) : _nextQuestion(), style: FilledButton.styleFrom( padding: const EdgeInsets.all(16.0), backgroundColor: ask_state == -1 ? null : (v.questions[_currentQuestionIndex].correct == v.questions[_currentQuestionIndex].answers .indexOf(option) ? Colors.green : Colors.red), ), child: Text(option))); }, ), if (ask_state != -1) Text( v.questions[_currentQuestionIndex].explanation, style: const TextStyle( fontSize: 15.0, fontWeight: FontWeight.bold, ), ) ], ), ), ); } }