Quiz: The Question
Part of the Projects section of Coddy's Flutter journey. Lesson 10 of 36.
The second app is a quiz about Flutter itself: a question, four answers to tap, green for right and red for wrong, a score and a results screen.
The questions are already in the starter. Each one is a Question with its text, its four answers and the position of the right one:
Question('Which language do you write Flutter apps in?',
['Kotlin', 'Swift', 'Dart', 'JavaScript'], 2),Positions start at 0, so 2 is 'Dart'. The state keeps _index, the question you are on, and questions[_index] is that question.
The answers are a collection for inside the Column: one button per answer. FilledButton.tonal is a soft filled button in the theme's color, good for a set of choices. With crossAxisAlignment: CrossAxisAlignment.stretch the column makes every child as wide as it is, so all four buttons line up edge to edge.
Challenge
EasyShow the first question:
- add
int _index = 0;to the state - replace the
Centerwith aColumnin 24 pixels of padding that stretches its children across - in it: the question's text in the theme's
headlineSmallstyle, 24 pixels of space, then aFilledButton.tonalfor each answer, with 16 pixels of padding inside and 12 pixels under each one
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> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Flutter Quiz')),
body: const Center(
child: Text('Your quiz goes here'),
),
);
}
}
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