测验:结果消息
本课属于 Coddy Flutter 学习旅程的“项目”单元。第 18 课,共 36 课。
“答对了 5 题,共 5 题”值得配上更丰富的展示,而不只是一行文字。用一个醒目的图标和符合结果的消息为测验画上句号:满分时显示奖杯,大部分答对时竖起大拇指,其他情况则给予鼓励。
从最好到最差检查 3 种结果,可以使用 if / else if / else。顺序很重要:满分也意味着答对了一半以上,所以要先检查满分。
if (score == total) {
message = 'Perfect!';
icon = Icons.emoji_events;
} else if (score * 2 >= total) {
message = 'Well done!';
icon = Icons.thumb_up;
} else {
message = 'Keep practicing!';
icon = Icons.school;
}score * 2 >= total表示“至少一半”,无需进行任何舍入:答对 5 题中的 3 题会通过,答对 5 题中的 2 题则不会。
在 if 之前声明 message、icon 和 color,先不赋值。Dart 会检查每个分支是否都为它们赋了值,然后你才能使用它们。
这是测验的最后一课。检查会运行完整的一轮,包括颜色、得分、结果和“再玩一次”。
挑战
中等在结果界面中,分数上方:
- 满分时显示
Perfect!和琥珀色的Icons.emoji_events - 得分至少达到一半时显示
Well done!和绿色的Icons.thumb_up - 得分低于一半时显示
Keep practicing!和主题主色的Icons.school
图标大小为 96 像素,接着留出 16 像素的间距,然后显示使用 headlineMedium 的消息,再留出 8 像素,最后显示使用 titleMedium 的分数行。
亲手试试
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;
int _score = 0;
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;
if (answer == _question.correct) {
_score++;
}
});
}
Future<void> _next() async {
if (!_isLast) {
setState(() {
_index++;
_picked = null;
});
return;
}
await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ResultsScreen(score: _score, total: questions.length),
),
);
setState(() {
_index = 0;
_picked = null;
_score = 0;
});
}
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'),
actions: [
Padding(
padding: const EdgeInsets.only(right: 16),
child: Center(
child: Text('Score: $_score', style: textTheme.titleMedium),
),
),
],
),
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: 8),
LinearProgressIndicator(
value: (_index + 1) / questions.length,
minHeight: 8,
borderRadius: BorderRadius.circular(4),
),
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) ...[
const SizedBox(height: 12),
Text(
_picked == question.correct
? 'Correct!'
: 'The answer is ${question.answers[question.correct]}',
textAlign: TextAlign.center,
style: textTheme.titleMedium,
),
const SizedBox(height: 16),
FilledButton(
onPressed: _next,
child: Text(_isLast ? 'See results' : 'Next'),
),
],
],
),
),
);
}
}
class ResultsScreen extends StatelessWidget {
const ResultsScreen({super.key, required this.score, required this.total});
final int score;
final int total;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Results')),
body: Center(
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(
'You scored $score out of $total',
style: Theme.of(context).textTheme.headlineSmall,
),
const SizedBox(height: 32),
FilledButton.icon(
onPressed: () => Navigator.pop(context),
icon: const Icon(Icons.replay),
label: const Text('Play again'),
),
],
),
),
),
);
}
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
项目中的所有课
自己练习: Flutter 在线编译器