Untitled
import 'package:flutter/material.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'MCQ Test App', theme: ThemeData( primarySwatch: Colors.blue, ), home: MCQTestScreen(), ); } } class MCQTestScreen extends StatefulWidget { @override _MCQTestScreenState createState() => _MCQTestScreenState(); } class _MCQTestScreenState extends State<MCQTestScreen> { int _currentQuestionIndex = 0; int _score = 0; final List<Map<String, dynamic>> _questions = [ { 'question': 'What is the capital of France?', 'options': ['Berlin', 'Madrid', 'Paris', 'Rome'], 'correctAnswer': 'Paris', }, { 'question': 'Which planet is known as the Red Planet?', 'options': ['Earth', 'Mars', 'Jupiter', 'Saturn'], 'correctAnswer': 'Mars', }, { 'question': 'Who wrote "To Kill a Mockingbird"?', 'options': ['Harper Lee', 'Mark Twain', 'J.K. Rowling', 'Ernest Hemingway'], 'correctAnswer': 'Harper Lee', }, ]; void _answerQuestion(String selectedAnswer) { if (selectedAnswer == _questions[_currentQuestionIndex]['correctAnswer']) { setState(() { _score++; }); } if (_currentQuestionIndex < _questions.length - 1) { setState(() { _currentQuestionIndex++; }); } else { _showResultDialog(); } } void _showResultDialog() { showDialog( context: context, builder: (BuildContext context) { return AlertDialog( title: Text('Test Result'), content: Text('Your score is $_score out of ${_questions.length}.'), actions: [ TextButton( onPressed: () { Navigator.of(context).pop(); setState(() { _currentQuestionIndex = 0; _score = 0; }); }, child: Text('Restart'), ), ], ); }, ); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('MCQ Test'), ), body: Padding( padding: const EdgeInsets.all(16.0), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Text( _questions[_currentQuestionIndex]['question'], style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold), ), SizedBox(height: 20), ...(_questions[_currentQuestionIndex]['options'] as List<String>).map((option) { return ElevatedButton( onPressed: () => _answerQuestion(option), child: Text(option), ); }).toList(), SizedBox(height: 20), Text( 'Question ${_currentQuestionIndex + 1} of ${_questions.length}', textAlign: TextAlign.center, style: TextStyle(fontSize: 16), ), ], ), ), ); } }
Leave a Comment