Menu
CoddyTech

测验:下一题

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

一道题还不算测验。你回答后,“下一题”按钮应该带你进入下一题,顶部的一行文字应该显示你当前的位置。

继续答题需要在一次 setState 中完成两项更改:索引加 1,并清除答案,这样新题目就会以没有颜色的状态开始:

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

只有在你已经回答问题且当前不是最后一题时,这个按钮才有用,因为最后一题后面没有下一题(结果页会稍后添加)。集合 if 只会在此时添加按钮:if (_answered && !_isLast) FilledButton(...)。

人们从 1 开始计数,列表从 0 开始计数。标签显示 _index + 1:'Question ${_index + 1} of ${questions.length}'。${...} 这种形式可以让你在字符串中放入整个表达式,而不只是名称。

challenge icon

挑战

中等

切换题目:

  • 添加一个 getter _isLast,让它在最后一道题时返回 true,并添加理论部分中的 _next 方法
  • 在题目上方,使用主题的 labelLarge 样式显示 Question 1 of 5(使用实际数字),然后留出 24 像素的间距
  • 在答案下方,当你已作答且当前题目不是最后一道时,显示一个标有 Next 的 FilledButton,点击后调用 _next

亲手试试

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;

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

  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.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]),
                ),
              ),
          ],
        ),
      ),
    );
  }
}
quiz icon自我测试

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

项目中的所有课

自己练习: Flutter 在线编译器