Menu
CoddyTech

Quiz: Punktestand

Teil des Abschnitts Projekte der Flutter-Journey von Coddy. Lektion 13 von 36.

Ein Quiz macht mehr Spaß, wenn du sehen kannst, wie du dich schlägst. Speichere den Punktestand im Zustand, addiere für jede richtige Antwort einen Punkt und zeige ihn in der oberen Leiste an.

Am besten zählst du in _pick, innerhalb desselben setState, in dem die Antwort gespeichert wird. Vergleiche die gegebene Antwort answer mit der richtigen:

setState(() {
  _picked = answer;
  if (answer == _question.correct) {
    _score++;
  }
});

Die Schutzabfrage am Anfang von _pick verhindert bereits einen zweiten Tipp, sodass jede Frage höchstens einen Punkt bringen kann.

Eine AppBar nimmt actions: entgegen, eine Liste von Widgets an ihrem rechten Ende. Platziere dort den Punktestand, eingebettet in ein Center, damit er mittig in der Höhe der Leiste sitzt, und füge rechts 16 Pixel Abstand hinzu.

challenge icon

Aufgabe

Mittel

Führe den Punktestand:

  • füge dem Zustand int _score = 0; hinzu
  • erhöhe ihn in _pick um eins, wenn die Antwort richtig ist
  • zeige Score: 0 (mit dem tatsächlichen Punktestand) in der actions-Leiste oben an, im Stil titleMedium des Themes, zentriert und mit 16 Pixeln Abstand rechts

Probier es selbst

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;
  bool get _isLast => _index == questions.length - 1;

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

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

  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 ${_index + 1} of ${questions.length}',
              style: textTheme.labelLarge,
            ),
            const SizedBox(height: 24),
            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]),
                ),
              ),
            if (_answered && !_isLast)
              FilledButton(
                onPressed: _next,
                child: const Text('Next'),
              ),
          ],
        ),
      ),
    );
  }
}
quiz iconTeste dich selbst

Diese Lektion enthält ein kurzes Quiz. Starte die Lektion, um es zu beantworten und deinen Fortschritt zu speichern.

Alle Lektionen in Projekte

Übe selbstständig: Online-Flutter-Compiler