Menu
CoddyTech

测验:正确还是错误

本课属于 Coddy Flutter 学习旅程的“项目”单元。第 11 课,共 36 课。

点选一个答案后,测验应立即告诉你结果:答对时显示绿色,答错时显示红色,无论答对还是答错,正确答案都会显示为绿色,这样你就能学会它。

状态需要记住你点选了哪个答案。在你点选答案之前,int? _picked 的值是 null,所以 _picked != null 表示你已经作答。作答后,按钮就不再响应点击:_pick 的第一行是一个保护检查。

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

一个小函数负责计算每个按钮的颜色。null 表示“没有指定颜色”,按钮会保留主题颜色:

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

现在,按钮需要知道自己的位置,而不只是文本,因此循环会计数:for (int i = 0; i < question.answers.length; i++) 会依次使用 i 的值 0、1、2 和 3。

challenge icon

挑战

困难

为答案设置颜色:

  • 添加理论部分中的 int? _picked、getter _question 和 _answered,以及方法 _pick 和 _colorFor
  • 使用 for (int i = 0; ...) 按位置遍历答案
  • 每个按钮都调用 _pick(i);它的 backgroundColor 为 _colorFor(i),有颜色时按钮文本为白色

亲手试试

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;

  @override
  Widget build(BuildContext context) {
    final question = questions[_index];
    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 (String answer in question.answers)
              Padding(
                padding: const EdgeInsets.only(bottom: 12),
                child: FilledButton.tonal(
                  style: FilledButton.styleFrom(
                    padding: const EdgeInsets.all(16),
                  ),
                  onPressed: () {},
                  child: Text(answer),
                ),
              ),
          ],
        ),
      ),
    );
  }
}
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

项目中的所有课

自己练习: Flutter 在线编译器