Menu
CoddyTech

퀴즈: 정답 또는 오답

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

답을 탭하면 퀴즈가 바로 알려 줍니다. 정답이면 초록색, 오답이면 빨간색으로 표시하고, 어느 쪽이든 정답은 초록색으로 표시해 학습할 수 있게 합니다.

상태에는 탭한 답을 기억해야 합니다. 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 컴파일러