Menu
CoddyTech

퀴즈: 다음 질문

Coddy Flutter 여정의 프로젝트 섹션에 포함된 레슨. 36개 중 12번째.

질문 하나만으로는 퀴즈라고 할 수 없습니다. 답을 고른 후에는 다음 버튼을 눌러 다음 질문으로 넘어가고, 맨 위의 줄에는 현재 위치가 표시되어야 합니다.

다음으로 넘어가는 과정은 하나의 setState 안에서 두 가지를 바꿉니다. 인덱스를 올리고 답을 지워서, 새 질문은 색이 없는 상태로 시작합니다.

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

답을 고른 뒤에만 버튼이 의미가 있으며, 다음 질문이 없는 마지막 질문에서는 버튼을 표시하지 않습니다(결과 화면은 나중에 추가합니다). 컬렉션 if를 사용하면 그때만 버튼을 추가할 수 있습니다. if (_answered && !_isLast) FilledButton(...).

사람은 1부터 세고, 목록은 0부터 셉니다. 라벨에는 _index + 1이 표시됩니다. 'Question ${_index + 1} of ${questions.length}'. ${...} 형식을 사용하면 문자열에 이름뿐 아니라 전체 표현식도 넣을 수 있습니다.

challenge icon

챌린지

중급

질문을 진행하세요:

  • 마지막 질문에서 true가 되는 게터 _isLast와 이론에 나온 _next 메서드를 추가하세요
  • 질문 위에 테마의 labelLarge 스타일로 Question 1 of 5(실제 숫자를 사용)를 표시한 다음, 24픽셀의 간격을 두세요
  • 답변 아래에, 답변을 선택했고 마지막 질문이 아니라면 _next를 호출하는 Next라는 레이블의 FilledButton을 표시하세요

직접 해보기

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 컴파일러