Simple Quiz App Using Flutter



In this tutorial, we'll be creating a Quiz App application in Flutter,

Our app creates an interactive quiz app . By the end of this tutorial, you'll have a interactive quiz app that you can run on both Android and iOS devices.


Source Code for the main.dart file




Add the following Code inside your main.dart file :


             
import 'package:flutter/material.dart';
import 'package:quiz_app/screens/quiz_screen.dart';

void main() {
runApp(const MainApp());
}

class MainApp extends StatelessWidget {
const MainApp({super.key});

@override
Widget build(BuildContext context) {
return MaterialApp(
    debugShowCheckedModeBanner: false,

    home: const QuizScreen(),
);
}
}
        
        


Source Code for the questions.dart file




Add the following Code inside your questions.dart file :


            
class QuestionModal {
    final String question;
    final List< String> options;
    final int correctAnswerIndex;
    
    const QuestionModal({
        required this.correctAnswerIndex,
        required this.question,
        required this.options,
    });
    }
    
    const List< QuestionModal> questions = [
    QuestionModal(
    question: '1. What is the capital of France?',
    correctAnswerIndex: 1,
    options: [
    (a) Madrid',
    (b) Paris',
    (c) Berlin',
    (d) Rome',
    ],
    ),
    QuestionModal(
        question: '2. In what continent is Brazil located?',
        correctAnswerIndex: 3,
        options: [
        (a) Europe',
        (b) Asia',
        (c) North America',
        (d) South America',
        ],
    ),
    QuestionModal(
        question: '3. What is the largest planet in our solar system?',
        correctAnswerIndex: 1,
        options: [
        (a) Earth',
        (b) Jupiter',
        (c) Saturn',
        (d) Venus',
        ],
    ),
    QuestionModal(
        question: '4. What is the longest river in the world?',
        correctAnswerIndex: 0,
        options: [
        (a) Nile',
        (b) Amazon',
        (c) Mississippi',
        (d) Danube',
        ],
    ),
    QuestionModal(
        question: '5. Who is the main character in the Harry Potter series?',
        correctAnswerIndex: 2,
        options: [
        (a) Hermione Granger',
        (b) Ron Weasley',
        (c) Harry Potter',
        (d) Neville Longbottom',
        ],
    ),
    QuestionModal(
        question: '6. What is the smallest planet in our solar system?',
        correctAnswerIndex: 3,
        options: [
        (a) Venus',
        (b) Mars',
        (c) Earth',
        (d) Mercury',
        ],
    ),
    QuestionModal(
        question: '7. Who wrote the play Romeo and Juliet?',
        correctAnswerIndex: 0,
        options: [
        (a) William Shakespeare',
        (b) Oscar Wilde',
        (c) Jane Austen',
        (d) Charles Dickens',
        ],
    ),
    QuestionModal(
        question: '8. What is the highest mountain in the world?',
        correctAnswerIndex: 1,
        options: [
        (a) Mont Blanc',
        (b) Everest',
        (c) Kilimanjaro',
        (d) Aconcagua',
        ],
    ),
    QuestionModal(
        question:
        '9. What is the name of the famous painting by Leonardo da Vinci that depicts a woman?',
        correctAnswerIndex: 3,
        options: [
        (a) Starry Night',
        (b) The Persistence of Memory',
        (c) The Last Supper',
        (d) Mona Lisa',
        ],
    ),
    ];
                
                
             
             
            


Source Code for the answer_card.dart file




Add the following Code inside your answer_card.dart file :


             
import 'package:flutter/material.dart';

/*
    If (no options is chosen)
    all answer cards should have default style
    all buttons should be enabled
    else
    all button should be disabled
    if (correct option is chosen)
        answer should be highlighted as green
    else
        answer should be highlighted as red
        correct answer should be highlighted as green
*/

class AnswerCard extends StatelessWidget {
    const AnswerCard({
    super.key,
    required this.question,
    required this.isSelected,
    required this.currentIndex,
    required this.correctAnswerIndex,
    required this.selectedAnswerIndex,
    });

    final String question;
    final bool isSelected;
    final int? correctAnswerIndex;
    final int? selectedAnswerIndex;
    final int currentIndex;

    @override
    Widget build(BuildContext context) {
    bool isCorrectAnswer = currentIndex == correctAnswerIndex;
    bool isWrongAnswer = !isCorrectAnswer && isSelected;
    return Padding(
        padding: const EdgeInsets.symmetric(
        vertical: 10.0,
        ),
        child:
        selectedAnswerIndex != null
        // if one option is chosen
            ? Container(
        height: 70,
        padding: const EdgeInsets.all(16.0),
        decoration: BoxDecoration(
            color: Colors.white24,
            borderRadius: BorderRadius.circular(25),
            border: Border.all(
            width: 2,
            color: isCorrectAnswer
                ? Colors.green
                : isWrongAnswer
                ? Colors.red
                : Colors.white,
            ),
        ),
        child: Row(
            children: [
            Expanded(
                child: Text(
                question,
                style: const TextStyle(
                    fontSize: 16,
                ),
                ),
            ),
            const SizedBox(height: 10),
            isCorrectAnswer
                ? buildCorrectIcon()
                : isWrongAnswer
                ? buildWrongIcon()
                : const SizedBox.shrink(),
            ],
        ),
        )
        // If no option is selected
            : Container(
        height: 70,
        padding: const EdgeInsets.all(16.0),
        decoration: BoxDecoration(
            color: Colors.white24,
            borderRadius: BorderRadius.circular(25),
            border: Border.all(
            color: Colors.white,
            ),
        ),
        child: Row(
            children: [
            Expanded(
                child: Text(
                question,
                style: const TextStyle(
                    fontSize: 16,
                    color: Colors.white
                ),
                ),
            ),
            ],
        ),
        ),
    );
    }
}

Widget buildCorrectIcon() => const CircleAvatar(
    radius: 15,
    backgroundColor: Colors.green,
    child: Icon(
    Icons.check,
    color: Colors.white,
    ),
);

Widget buildWrongIcon() => const CircleAvatar(
    radius: 15,
    backgroundColor: Colors.red,
    child: Icon(
    Icons.close,
    color: Colors.white,
    ),
);
                
           
             
            

Source Code for the next_button.dart file




Add the following Code inside your next_button.dart file :


             
import 'package:flutter/material.dart';

class RectangularButton extends StatelessWidget {
    const RectangularButton({
    super.key,
    required this.onPressed,
    required this.label,
    });

    final VoidCallback? onPressed;
    final String label;

    @override
    Widget build(BuildContext context) {
    return
        TextButton(
        onPressed: onPressed,
        child: SizedBox(
            height: 50,
            width: double.infinity,
            child: Card(
            color: onPressed != null ? Colors.orange.shade600 : Colors.orange.shade500,
            child: Center(
                child: Text(
                label,
                style: const TextStyle(
                    letterSpacing: 2,
                    fontSize: 25,
                    fontWeight: FontWeight.w400,
                    color: Colors.black
                ),
                ),
            ),
            ),
        ),
        );
    }
}
            
             
            

Source Code for the quiz_screen.dart file




Add the following Code inside your quiz_screen.dart file :


             
import 'package:flutter/material.dart';
import 'package:quiz_app/models/questions.dart';
import 'package:quiz_app/widgets/answer_card.dart';
import 'package:quiz_app/widgets/next_button.dart';
import 'package:quiz_app/screens/result_screen.dart';

class QuizScreen extends StatefulWidget {
    const QuizScreen({super.key});

    @override
    State< QuizScreen> createState() => _QuizScreenState();
}

class _QuizScreenState extends State< QuizScreen> {

    int? selectedAnswerIndex;
    int questionIndex = 0;
    int score = 0;


    void pickAnswer(int value) {
    setState(() {
        selectedAnswerIndex = value;
        final question = questions[questionIndex];


        if (selectedAnswerIndex == question.correctAnswerIndex) {
        score++;
        }
    });
    }

    void goToNextQuestion() {
    setState(() {
        if (questionIndex < questions.length - 1) {
        questionIndex++;
        selectedAnswerIndex = null;
        }
    });
    }


    @override
    Widget build(BuildContext context) {
    final question = questions[questionIndex];
    bool isLastQuestion = questionIndex == questions.length - 1;


    return Scaffold(
        backgroundColor: Colors.deepPurple,
        appBar: AppBar(
        backgroundColor: Colors.deepPurpleAccent,
        title: const Text('Quiz App'),
        centerTitle: true,
        ),
        body:
        Padding(
        padding: const EdgeInsets.all(24.0),
        child:
        Column(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
            Text(
                question.question,
                style: const TextStyle(
                    fontSize: 21,
                    color: Colors.white
                ),
                textAlign: TextAlign.center,
            ),
            ListView.builder(
                shrinkWrap: true,
                itemCount: question.options.length,
                itemBuilder: (context, index) {
                return GestureDetector(
                    onTap: selectedAnswerIndex == null
                    ? () => pickAnswer(index)
                : null,
                    child: AnswerCard(
                    currentIndex: index,
                    question: question.options[index],
                    isSelected: selectedAnswerIndex == index,
                    selectedAnswerIndex: selectedAnswerIndex,
                    correctAnswerIndex: question.correctAnswerIndex,
                    ),
                );
                },
            ),

            isLastQuestion
                ? RectangularButton(
                onPressed: () {
                Navigator.of(context).pushReplacement(
                    MaterialPageRoute(
                    builder: (_) => ResultScreen(
                        score: score,
                    ),
                    ),
                );
                },
                label: 'Finish',
            )
                : RectangularButton(
                onPressed:
                selectedAnswerIndex != null ? goToNextQuestion : null,
                label: 'Next',
            ),

            ],
        ),
        ),
    );
    }
}
                

             
            


Source Code for the result_screen.dart file




Add the following Code inside your result_screen.dart file :


             
import 'package:flutter/material.dart';
import 'package:quiz_app/models/questions.dart';
import 'package:quiz_app/screens/quiz_screen.dart';
import 'package:quiz_app/widgets/next_button.dart';

class ResultScreen extends StatelessWidget {
    const ResultScreen({
    super.key,
    required this.score,
    });

    final int score;

    @override
    Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Colors.deepPurpleAccent,
        body: Center(
        child: Column(

            children: [
            SizedBox(
                height: 150,
            ),
            const Text(
                'Your Score: ',
                style: TextStyle(
                    fontSize: 34,
                    fontWeight: FontWeight.w500,
                    color: Colors.white
                ),
            ),
            SizedBox(
                height: 150,
            ),
            Stack(
                alignment: Alignment.center,
                children: [
                SizedBox(
                    height: 250,
                    width: 250,
                    child: CircularProgressIndicator(
                    strokeWidth: 12,
                    value: score / 9,
                    color: Colors.lightGreen,
                    backgroundColor: Colors.white,
                    ),
                ),
                Column(
                    children: [
                    Text(
                        score.toString() + "/9",
                        style: const TextStyle(fontSize: 80,
                            color: Colors.white),
                    ),
                    const SizedBox(height: 10),
                    Text(
                        '${(score / questions.length * 100).round()}%',
                        style: const TextStyle(fontSize: 30,color: Colors.white),
                    ),




                    ],
                ),
                ],
            ),
            SizedBox(
                height: 150,
            ),

            RectangularButton(
                onPressed: () {
                Navigator.of(context).pushReplacement(
                    MaterialPageRoute(
                    builder: (_) => QuizScreen(),
                    ),
                );
                },
                label: 'Restart',
            )

            ],
        ),
        ),
    );
    }
}
                


             
            


The Output is shown below :




Contact Us

REACH US

SERVICES

  • CODING
  • ON-LINE PREPARATION
  • JAVA & PYTHON

ADDRESS

B-54, Krishna Bhawan, Parag Narain Road, Near Butler Palace Colony Lucknow
Contact:+ 919839520987
Email:info@alexsir.com