Menu
CoddyTech

Quiz: Next Question

Part of the Projects section of Coddy's Flutter journey. Lesson 12 of 36.

One question is not a quiz. After you answer, a Next button should take you to the next question, and a line at the top should say where you are.

Moving on is two changes in one setState: the index goes up, and the answer is forgotten, so the new question starts with no colors:

void _next() {
  setState(() {
    _index++;
    _picked = null;
  });
}

The button only makes sense once you have answered, and not on the last question, where there is no next one (the results screen comes later). A collection if adds it only then: if (_answered && !_isLast) FilledButton(...).

People count from 1, lists count from 0. The label shows _index + 1: 'Question ${_index + 1} of ${questions.length}'. The ${...} form lets you put a whole expression in a string, not only a name.

challenge icon

Challenge

Medium

Move through the questions:

  • add a getter _isLast that is true on the last question, and the _next method from the theory
  • above the question, show Question 1 of 5 (with the real numbers) in the theme's labelLarge style, then 24 pixels of space
  • under the answers, once you have answered and the question is not the last, show a FilledButton labelled Next that calls _next

Try it yourself

import 'package:flutter/material.dart';

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

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
      ),
      home: const QuizScreen(),
    );
  }
}

class Question {
  const Question(this.text, this.answers, this.correct);

  final String text;
  final List<String> answers;
  final int correct;
}

const List<Question> questions = [
  Question('Which widget stacks its children from top to bottom?', ['Row', 'Column', 'Stack', 'Wrap'], 1),
  Question('Which language do you write Flutter apps in?', ['Kotlin', 'Swift', 'Dart', 'JavaScript'], 2),
  Question('What does setState do?', ['Rebuilds the widget', 'Saves the app', 'Closes the screen', 'Plays a sound'], 0),
  Question('Which widget shows a list you can scroll?', ['Container', 'SizedBox', 'Padding', 'ListView'], 3),
  Question('Which widget adds space around its child?', ['Padding', 'Center', 'Icon', 'Text'], 0),
];

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

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

class _QuizScreenState extends State<QuizScreen> {
  int _index = 0;
  int? _picked;

  Question get _question => questions[_index];
  bool get _answered => _picked != null;

  void _pick(int answer) {
    if (_answered) return;
    setState(() {
      _picked = answer;
    });
  }

  Color? _colorFor(int answer) {
    if (!_answered) return null;
    if (answer == _question.correct) return Colors.green;
    if (answer == _picked) return Colors.red;
    return null;
  }

  @override
  Widget build(BuildContext context) {
    final question = _question;
    final textTheme = Theme.of(context).textTheme;
    return Scaffold(
      appBar: AppBar(title: const Text('Flutter Quiz')),
      body: Padding(
        padding: const EdgeInsets.all(24),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            Text(question.text, style: textTheme.headlineSmall),
            const SizedBox(height: 24),
            for (int i = 0; i < question.answers.length; i++)
              Padding(
                padding: const EdgeInsets.only(bottom: 12),
                child: FilledButton.tonal(
                  style: FilledButton.styleFrom(
                    backgroundColor: _colorFor(i),
                    foregroundColor: _colorFor(i) == null ? null : Colors.white,
                    padding: const EdgeInsets.all(16),
                  ),
                  onPressed: () => _pick(i),
                  child: Text(question.answers[i]),
                ),
              ),
          ],
        ),
      ),
    );
  }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Projects

Practice on your own: Online Flutter compiler