The Wayback Machine - https://web.archive.org/web/20240909174232/https://www.geeksforgeeks.org/basic-quiz-app-in-flutter-api/
Open In App

Basic Quiz App In Flutter API

Last Updated : 03 Apr, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Flutter API is an open-source software development kit for building beautiful UI which is natively compiled. Currently, it is available as a stable version for iOS and Android OS.

In this app we are going to have the features or modules mentioned below:

  • Five multiple-choice questions ( more questions can be added ).
  • Four selectable options for each question in the form of buttons except the last one.
  • The score will be calculated based on the option selected for each question (Internally).
  • And based on the final score a remark will be shown at the end of the quiz in addition to the score and restart button.
  • There are two screens in the app home (where questions will be shown) and the result screen ( where score and remark will be shown).
  • The whole app will be separated into five different modules namely main.dart, question.dart, answer.dart, quiz.dart and result.dart.

Making this app will give you a good revision of flutter and dart basics. As we are covering a lot of concepts such as:

  • Showing Widgets on the screen.
  • Recycling Widgets.
  • Changing Screens.
  • Internal Logic
  • and else.

To start making the app we first have to create a flutter project which will give us many files and folders. In the Lib folder, there is a main.dart file is already present. Now in the same folder rest, four files should be created:- 

  • question.dart
  • answer.dart
  • quiz.dart and
  • result.dart

Step 1: In step one we are going to

  • Create MyApp class and make it stateful.
  • Add questions for the home screen.
  • Create a widget tree for the home screen.

Starting with the main.dart file

Dart
import 'package:flutter/material.dart';

import './quiz.dart';
import './result.dart';

void main() => runApp(const MyApp());

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _MyAppState();
  }
}

class _MyAppState extends State<MyApp> {
  final _questions = const [
    {
      'questionText': 'Q1. Who created Flutter?',
      'answers': [
        {'text': 'Facebook', 'score': -2},
        {'text': 'Adobe', 'score': -2},
        {'text': 'Google', 'score': 10},
        {'text': 'Microsoft', 'score': -2},
      ],
    },
    {
      'questionText': 'Q2. What is Flutter?',
      'answers': [
        {'text': 'Android Development Kit', 'score': -2},
        {'text': 'IOS Development Kit', 'score': -2},
        {'text': 'Web Development Kit', 'score': -2},
        {
          'text':
              'SDK to build beautiful IOS, Android, Web & Desktop Native Apps',
          'score': 10
        },
      ],
    },
    {
      'questionText': ' Q3. Which programming language is used by Flutter',
      'answers': [
        {'text': 'Ruby', 'score': -2},
        {'text': 'Dart', 'score': 10},
        {'text': 'C++', 'score': -2},
        {'text': 'Kotlin', 'score': -2},
      ],
    },
    {
      'questionText': 'Q4. Who created Dart programming language?',
      'answers': [
        {'text': 'Lars Bak and Kasper Lund', 'score': 10},
        {'text': 'Brendan Eich', 'score': -2},
        {'text': 'Bjarne Stroustrup', 'score': -2},
        {'text': 'Jeremy Ashkenas', 'score': -2},
      ],
    },
    {
      'questionText':
          'Q5. Is Flutter for Web and Desktop available in stable version?',
      'answers': [
        {
          'text': 'Yes',
          'score': -2,
        },
        {'text': 'No', 'score': 10},
      ],
    },
  ];

  var _questionIndex = 0;
  var _totalScore = 0;

  void _resetQuiz() {
    setState(() {
      _questionIndex = 0;
      _totalScore = 0;
    });
  }

  void _answerQuestion(int score) {
    _totalScore += score;

    setState(() {
      _questionIndex = _questionIndex + 1;
    });
    // ignore: avoid_print
    print(_questionIndex);
    if (_questionIndex < _questions.length) {
      // ignore: avoid_print
      print('We have more questions!');
    } else {
      // ignore: avoid_print
      print('No more questions!');
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Geeks for Geeks'),
          backgroundColor: const Color(0xFF00E676),
        ),
        body: Padding(
          padding: const EdgeInsets.all(30.0),
          child: _questionIndex < _questions.length
              ? Quiz(
                  answerQuestion: _answerQuestion,
                  questionIndex: _questionIndex,
                  questions: _questions,
                ) //Quiz
              : Result(_totalScore, _resetQuiz),
        ), //Padding
      ), //Scaffold
      debugShowCheckedModeBanner: false,
    ); //MaterialApp
  }
}

In Flutter main.dart file is the entry point from which the code starts executing. In the main.dart file firstly material design package has been imported in addition to quiz.dart and result.dart . Then a function runApp has been created with parameter as MyApp. After the declaration of class MyApp which is a stateful widget, the state of class MyApp has been laid out. Now that is followed by the four questions along with their respective answer options & score. And at the end, we have the widget tree for the home screen, which shows the appBar with title, body with the questions and options. At the last, the debug banner has been disabled. We have classes like Quiz or Result, that will be defined in the following pages.

Step 2: In step two we will create

  • Class Quiz (used in the home screen)
  • Widget tree for class Quiz

quiz.dart

Dart
import 'package:flutter/material.dart';

import './answer.dart';
import './question.dart';

class Quiz extends StatelessWidget {
  final List<Map<String, Object>> questions;
  final int questionIndex;
  final Function answerQuestion;

  const Quiz({
    Key? key,
    required this.questions,
    required this.answerQuestion,
    required this.questionIndex,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Question(
          questions[questionIndex]['questionText'].toString(),
        ), //Question
        ...(questions[questionIndex]['answers'] as List<Map<String, Object>>)
            .map((answer) {
          return Answer(
              () => answerQuestion(answer['score']), answer['text'].toString());
        }).toList()
      ],
    ); //Column
  }
}

This is the quiz.dart which was already imported in the main.dart file. In this file the class Quiz is being defined which is used in the main.dart file. Class Quiz has been extended as stateless widget as it need not change any time in the run cycle of the app, which is followed by constructor Quiz. Then we have the widget tree that defines the structure of the class Quiz which is basically the questions and their options. Again we have the class Question which will be defined in the question.dart file.

Step 3: In step three we will create

  • Class Question (again used in the home screen)
  • Widget tree for the class Question

question.dart

Dart
import 'package:flutter/material.dart';

class Question extends StatelessWidget {
  final String questionText;

  const Question(this.questionText, {Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      margin: const EdgeInsets.all(10),
      child: Text(
        questionText,
        style: const TextStyle(fontSize: 28),
        textAlign: TextAlign.center,
      ), //Text
    ); //Container
  }
}

This question.dart file has already been imported into the quiz.dart file, which uses the class Question. The class Question would be a stateless one similar to the Quiz it needs not change in the run cycle. Then we have the constructor Question which is followed by the widget tree that gives structure to the Question widget.

Step 4: In step four we will create

  • Class Answer (used in the home screen)
  • Widget tree for class Answer

answer.dart

Dart
import 'package:flutter/material.dart';

class Answer extends StatelessWidget {
  final Function selectHandler;
  final String answerText;

  const Answer(this.selectHandler, this.answerText, {Key? key})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    // use SizedBox for white space instead of Container
    return SizedBox(
      width: double.infinity,
      child: ElevatedButton(
        onPressed: selectHandler(),
        style: ButtonStyle(
            textStyle:
                MaterialStateProperty.all(const TextStyle(color: Colors.white)),
            backgroundColor: MaterialStateProperty.all(Colors.green)),
        child: Text(answerText),
      ),

      // RaisedButton is deprecated and should not be used
      // Use ElevatedButton instead

      // child: RaisedButton(
      //   color: const Color(0xFF00E676),
      //   textColor: Colors.white,
      //   onPressed: selectHandler(),
      //   child: Text(answerText),
      // ), //RaisedButton
    ); //Container
  }
}

This answer.dart file was also imported in the quiz.dart file. This file contains the Answer class which was used in the quiz.dart file. Again similar to Quiz and Question class Answer would also be stateless.  In the class Answer function, selectHandler and string answerText have been passed using the keyword final as they belong to the stateful widget and hence need to be specified immutable, and not doing so will result in a dart analysis warning. That is followed by the constructor and the usual widget tree to give it a structure.

Step 5: In the last step we will create

  • Class Result for (result screen)
  • Remark logic
  • Class Result widget tree

File: result.dart

Dart
// ignore_for_file: avoid_print

import 'package:flutter/material.dart';

class Result extends StatelessWidget {
  final int resultScore;
  final Function resetHandler;

  const Result(this.resultScore, this.resetHandler, {Key? key})
      : super(key: key);

  //Remark Logic
  String get resultPhrase {
    String resultText;
    if (resultScore >= 41) {
      resultText = 'You are awesome!';
      print(resultScore);
    } else if (resultScore >= 31) {
      resultText = 'Pretty likeable!';
      print(resultScore);
    } else if (resultScore >= 21) {
      resultText = 'You need to work more!';
    } else if (resultScore >= 1) {
      resultText = 'You need to work hard!';
    } else {
      resultText = 'This is a poor score!';
      print(resultScore);
    }
    return resultText;
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Text(
            resultPhrase,
            style: const TextStyle(fontSize: 26, fontWeight: FontWeight.bold),
            textAlign: TextAlign.center,
          ), //Text
          Text(
            'Score ' '$resultScore',
            style: const TextStyle(fontSize: 36, fontWeight: FontWeight.bold),
            textAlign: TextAlign.center,
          ), //Text
          TextButton(
            onPressed: resetHandler(),
            child: Container(
              color: Colors.green,
              padding: const EdgeInsets.all(14),
              child: const Text(
                'Restart Quiz',
                style: TextStyle(color: Colors.blue),
              ),
            ),
          ),
          // FlatButton is deprecated and should not be used
          // Use TextButton instead

          // FlatButton(
          //   child: Text(
          //     'Restart Quiz!',
          //   ), //Text
          //   textColor: Colors.blue,
          //   onPressed: resetHandler(),
          // ), //FlatButton
        ], //<Widget>[]
      ), //Column
    ); //Center
  }
}

This result.dart file had been imported in the main.dart file already as the class Result is defined in this file. Class results will not change in the app run cycle therefore it is a stateless widget. As subclasses or variables which are used in the stateful widget need to be made immutable keyword final has been used, it is followed by the Result keyword. After that, we have the resulting logic which decided which remark would be shown after the quiz bases on the final score. And at last, we have the widget tree that defines the structure of the class Result.

And now after completing the result.dart file our basic quiz app is completed now. We can preview the app in any physical device or emulator or even in the browser. It should look something like this.

After the app has been finalized, apk for the app can be generated by giving the command ‘flutter build apk’ in the terminal.



Previous Article
Next Article

Similar Reads

How to Build Advance Quiz App in Flutter?
This is a quiz app using Flutter and API. The working of this application is very simple, here we have two screens: screen one and screen two. Screen one is the stateless screen which means that it will not respond to any change on the screen. The second screen, is a stateful widget which means that the it will respond to changes on interaction by
10 min read
Is Flutter Worth Learning? Top 7 Reasons to Learn Flutter
In today's era, the usage of smartphones has increased exponentially and so has the use of mobile applications and websites. Meanwhile, considering future career prospects, learning web development and mobile app development is strongly recommended for all individuals. And when we come to mobile app development, there are two most-popular open-sour
5 min read
Flutter - Sharing Data Among Flutter Pages
In this article, we are going to find the solution for the problem statement "Import/send data from one page to another in flutter". Before going into the topic, there are some pre-requisites. Pre-requisites:Basics of dart programming language.Setting up Flutter in VS code or Setting up Flutter in Android Studio.Creating first flutter app | Hello W
4 min read
Flutter Quill - Rich Text Editor in Flutter Application
This post will explain how to integrate a rich text editor into your Flutter application so that it may enable rich text editing. There are many more things we can do with Flutter Quill, but they can get a little involved. The example below is a pretty basic demonstration of what we mean. Let's first discuss what flutter quill is and why we need it
5 min read
Flutter - Animated AlertDialog in Flutter
Animating an AlertDialog in Flutter involves using the Flutter animations framework to create custom animations for showing and hiding the dialogue. In this article, we are going to add an animation to an AlertDialog. A sample video is given below to get an idea about what we are going to do in this article. [video mp4="https://media.geeksforgeeks.
4 min read
Flutter - Different Types of Loading using Flutter EasyLoading
Flutter applications involve incorporating loading indicators to provide users with feedback during background operations. Flutter has a package for simplifying the process named flutter_easyloading package. This package easiest way to integrate loading indicators with various styles. In this article, we will implement different types of loading in
5 min read
Flutter Bloc - Basic Search
Flutter is a powerful tool to develop cool android and ios apps and much more like PWAs from a single code base. In this article, we will guide you on how you can design your Bloc architecture for the search module. GOAL: For starters, we will aim to create an app with a search field that can have consecutive search pages and save all the results.
3 min read
Flutter - Building an Alarm Clock App
Many applications like the Todo app, Exercise App, require alarm clocks to keep track of time in activities. Or if you want to create an alarm clock app for yourself, you will learn this today. If your app contains features like setting the alarm or setting the timer, how you can do this in Flutter? Don’t worry, it's easy with the flutter_alarm_clo
9 min read
How to Choose the Right Architecture Pattern For Your Flutter App?
One of the key decisions you'll make when building a Flutter app is selecting the right architecture pattern. The architecture pattern determines how your app's code is organized and how its different components interact with each other. Choosing the right architecture can make it easier to build, test, and maintain your app over time. In this arti
4 min read
A Hello World App using Flutter
Flutter is an app SDK for building high-performance, high-fidelity apps for iOS, Android, Web(beta), and desktop(technical preview) from a single codebase written in Dart Language. In this article, I will provide line by line explanation of how to build a simple Hello World App using Flutter. In Flutter everything is a Widget and using predefined w
4 min read
Advanced Calculator App using Flutter
Flutter SDK is an open-source software development kit for building beautiful UI which is natively compiled. In this article, we are going to create an advanced calculator app by using some advanced packages available in Flutter. In this app, you get some functionality. In this app you have only one screen in that screen we perform our whole calcul
4 min read
Flutter - Scratch Card View App
Scratch Card is one of the popular things that you can get to see on various shopping apps and payment apps. These Scratch Cards are used to offer rewards and cashback to users. It can have a wide range of use cases but it is primarily used to generate random rewards for the users of the application. In this article we are going to see how to imple
5 min read
Flutter - Dice Roller App
Here we will be building a simple dice app that rolls on click. For this, we will add a button and when we click on it the dice should roll. We can achieve this by wrapping Image Widget in a FlatButton Widget and changing dice images randomly in a callback function which is set to onPressed property of the FlatButton. We will create this app using
3 min read
Flutter - Splitting App into Widgets
Splitting an app into widgets refers to the breaking up of large widgets into smaller, more manageable widgets which can be inferred as smaller chunks of codes. The principal thing here is to understand when to split a widget into smaller ones. We are going to discuss when to split a widget and methods of how to perform this. When to Split Widgets
5 min read
Flutter - Best Alternatives for App Development
If you are a beginner and want to make some mobile apps, but you are confused about the technologies and frameworks for mobile app development offers, or if you are just curious to know what advantages flutter offers from its competitors then this article is for you. There are tons of options that a developer gets about the best trends and technolo
9 min read
Flutter - local state vs App-wide state
Local State (sometimes called UI state or Ephemeral State): It is a state which can be manageable in a single widget. There is no need for state management techniques(Bloc, redux, etc ) on this kind of state a Stateful Widget would suffice. Examples: Current page in a page view, current tab in the navigation bar. C/C++ Code import 'package:flutter/
3 min read
Flutter Story App
A mobile application called Flutter Story App enables users to read and share poetry, short tales, and other types of writing. The popular open-source mobile app development framework, Flutter, developed by Google, is used to build the app. Users may browse and find new content with ease because of the app's simple and user-friendly interface. Read
8 min read
Mask Detection App in Flutter
Nowadays in the situation of Covid, it is very important to wear a Mask and protect yourself and others. So this App helps to detect whether the person has worn the Mask or Not. In this Application, the Mask detection is done with the help of TensorFlow Lite. Follow the steps to implement Mask Detection in our Flutter App Add the dependency to pubs
7 min read
How to Dismiss the Virtual Keyboard in a Flutter App?
We all have faced situations after filling the text field the virtual keyboard does not go away automatically. We have to click on the back button of our smartphones to remove the virtual keyboard. So in this article, we will see how to dismiss the virtual keyboard in an app with just one tap. For this, we will be using the onTap() property of the
2 min read
How to Deploy Flutter Web App on Netlify?
In this article, we will deploy a counter flutter web app which is a single page application on netlify. Netlify: It is a web development platform that makes CI/CD, deployment, and scaled hosting. It supports multiple frameworks which include Flutter. It does not require money to deploy websites but is limited to certain features. Firstly, let's cr
3 min read
How to Build a Flutter App to Display Device Details?
Here we are going to build an android application using flutter that displays device information on which it is running. To display information about the device we are going to use a package called device_info_plus. Create Flutter Project: Now remove all the existing code and remove the test folder Create a basic app screen: C/C++ Code import 'pack
5 min read
How to Add Splash Screen in Flutter App?
We all have heard of Flutter right, it's a cross-platform application development tool. Flutter can be used to make Android, IOS, and Web applications with just one code base (Dart programming language). In this article let's see how we can add a splash screen to our applications. What is Splash Screen? When we open an application on our phones, th
3 min read
How to Install Flutter App on Android?
The hottest and trending cross-platform framework, Flutter is Google's SDK for crafting beautiful, fast user experiences for mobile, web, and desktop with just a single codebase, meaning you write for one, build for three. Flutter works with existing code, is used by developers and organizations around the world, and is free and open source. The he
4 min read
Flutter - Renaming a App
Flutter is a UI kit by Google. Flutter is a widely growing open-source framework, with many libraries getting published daily making android/iOS, web development easy. In this article, we will see the use of the library - "rename". Although there are other packages also, but this one is the most popular and holds null safety. While creating a proje
3 min read
Flutter - Creating App Intro Screens
Flutter is known for its easiness to create cross-platform applications. Either it is creating introduction screens for the app or any screen. We got an easy way to create Intros for the app using the intro_slider library of Flutter. In this article, we are going to implement it in the sample app. In this sample app, we are creating three slides, t
4 min read
How to Run a Flutter App on Android Emulator?
An emulator is a virtual device created to run programs/applications derived from the host system. An Android Emulator imitates an android device and is used to run and test android applications on your host system without requiring the presence of a physical android device. To run your flutter applications on an emulator is a bit of a task if you
3 min read
How to Use SystemNavigator.pop() to Exit App in Flutter?
In many applications, we need force to close the entire application. So in this article, we are going to do the same. We can use the SystemNavigator.pop() to exit the application. There is no need for additional packages. How to Use? Import the library First, we need to import the service package. C/C++ Code import 'package:flutter/services.dart';
2 min read
Flutter - How to Change App and Launcher Title in Different Platforms
Sometimes you notice that we have to change the App title in Android, and iOS apps, and the title for flutter web during or after loading. So in this article, we will cover all the places where we have to change the app title with different platforms. 1. Android App Title Change the android label name in File Path: android/app/src/main/AndroidManif
2 min read
How to Build a Video Calling App in Flutter?
Video Calling has become a necessary feature in most real-time communication applications used around the world. Its primary application is to connect people from all around the world along with other obvious applications. Chat applications like Facebook, WhatsApp, and Instagram all have video calling features. Zoom, Google Meet, Microsoft Teams, a
4 min read
How to Create Image Cropper App in Flutter?
Flutter is a robust framework that allows developers to create beautiful and responsive mobile applications. Images are an essential part of any mobile application, and developers need to be able to manipulate them effectively. Image cropping is a common task when working with images, and the image_cropper package is an excellent tool for achieving
8 min read
Article Tags :