Menu
CoddyTech

Trắc nghiệm: Câu hỏi tiếp theo

Thuộc phần Dự án trong hành trình Flutter của Coddy. Bài học 12 trên 36.

Một câu hỏi thì chưa thành bài trắc nghiệm. Sau khi bạn trả lời, nút Tiếp theo sẽ đưa bạn đến câu hỏi tiếp theo, còn một dòng ở đầu sẽ cho biết bạn đang ở đâu.

Chuyển sang câu hỏi tiếp theo cần hai thay đổi trong một setState: chỉ số tăng lên và câu trả lời bị xóa, để câu hỏi mới bắt đầu mà không có màu nào:

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

Nút này chỉ hợp lý sau khi bạn đã trả lời, và không xuất hiện ở câu hỏi cuối cùng vì không còn câu tiếp theo (màn hình kết quả sẽ xuất hiện sau). if trong collection chỉ thêm nút khi đó: if (_answered && !_isLast) FilledButton(...).

Mọi người đếm từ 1, còn danh sách đếm từ 0. Nhãn hiển thị _index + 1: 'Question ${_index + 1} of ${questions.length}'. Dạng ${...} cho phép bạn đặt cả một biểu thức trong chuỗi, không chỉ một tên.

challenge icon

Thử thách

Trung bình

Chuyển qua các câu hỏi:

  • thêm getter _isLast trả về true ở câu hỏi cuối cùng và phương thức _next trong phần lý thuyết
  • phía trên câu hỏi, hiển thị Question 1 of 5 (với các số thực tế) theo kiểu labelLarge của giao diện, sau đó chừa khoảng trống 24 pixel
  • bên dưới các đáp án, sau khi bạn trả lời và câu hỏi không phải câu cuối cùng, hiển thị FilledButton có nhãn Next gọi _next

Tự làm thử

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 iconTự kiểm tra

Bài học này có một bài trắc nghiệm ngắn. Bắt đầu bài học để trả lời và theo dõi tiến độ.

Tất cả bài học trong Dự án

Tự luyện tập: Trình biên dịch Flutter online