Quiz Screen
Loading preview
Starting the Flutter app
A showcase of Flutter's quiz screen functionality
import 'package:flutter/material.dart';
class QuizScreen extends StatefulWidget {
/// Called with the chosen option's index, or null when skipped. Without it
/// the demo shows a SnackBar.
final ValueChanged<int?>? onAnswer;
const QuizScreen({super.key, this.onAnswer});
@override
State<QuizScreen> createState() => _QuizScreenState();
}
class _QuizScreenState extends State<QuizScreen> {
var _selected = -1;
final _currentQuestion = 1;
final _totalQuestions = 5;
void _answer(int? choice) {
final onAnswer = widget.onAnswer;
if (onAnswer != null) {
onAnswer(choice);
return;
}
final message = choice == null ? 'Question skipped' : 'Answer submitted';
ScaffoldMessenger.of(context)
..hideCurrentSnackBar()
..showSnackBar(SnackBar(content: Text('$message (demo)')));
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Question $_currentQuestion of $_totalQuestions'),
leading: IconButton(
tooltip: 'Close quiz',
icon: const Icon(Icons.close),
onPressed: () => Navigator.of(context).pop(),
),
),
body: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
LinearProgressIndicator(value: _currentQuestion / _totalQuestions),
const SizedBox(height: 24),
Text(
'What is a Widget in Flutter?',
style: Theme.of(context).textTheme.titleLarge,
),
const SizedBox(height: 24),
RadioGroup<int>(
groupValue: _selected,
onChanged: (v) => setState(() => _selected = v ?? -1),
child: Column(
children: [
'A building block',
'A state manager',
'A layout engine',
'A database',
].asMap().entries.map((e) => RadioListTile<int>(
value: e.key,
title: Text(e.value),
)).toList(),
),
),
const Spacer(),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
TextButton(
onPressed: () => _answer(null),
child: const Text('Skip'),
),
FilledButton(
onPressed: _selected >= 0 ? () => _answer(_selected) : null,
child: const Text('Submit'),
),
],
),
],
),
),
);
}
}
Add it to your project
Copies the Dart source into your app, so you own it. Flutter SDK only, no extra packages.
First time? Run dart pub global activate fluttertemplates_dev, or read the CLI guide.
How it works
One hardcoded question renders through RadioGroup and RadioListTile, with _selected starting at -1. Submit stays disabled until an option is picked. It passes the index to onAnswer and Skip passes null, with a demo SnackBar when onAnswer is omitted. _currentQuestion and _totalQuestions are final, so the title and LinearProgressIndicator stay on 1 of 5, and no correct answer is stored anywhere.
Adapting it
- Add a question list holding options and the correct index, and make
_currentQuestionmutable. - In
_answer, score the choice, advance, then reset_selectedto-1. - Treat null as a skip, and show a results screen after
_totalQuestions.