퀴즈: 점수 기록
Coddy Flutter 여정의 프로젝트 섹션에 포함된 레슨. 36개 중 13번째.
퀴즈는 진행 상황을 확인할 수 있으면 더 재미있습니다. 상태에 점수를 저장하고, 정답을 맞힐 때마다 1점을 더한 다음 상단 표시줄에 점수를 표시하세요.
점수를 세기 가장 좋은 곳은 _pick입니다. 답을 저장하는 것과 같은 setState 안에서 처리하세요. 받은 답인 answer와 정답을 비교합니다.
setState(() {
_picked = answer;
if (answer == _question.correct) {
_score++;
}
});_pick 맨 위의 가드가 이미 두 번째 탭을 막으므로, 각 질문에서 얻을 수 있는 점수는 최대 1점입니다.
AppBar는 오른쪽 끝에 위젯 목록을 표시하는 actions:를 받습니다. 여기에 점수를 넣고, Center로 감싸서 표시줄 높이의 가운데에 오도록 하며, 오른쪽에 16픽셀의 패딩을 추가하세요.
챌린지
중급점수를 기록하세요:
- 상태에
int _score = 0;을 추가하세요 _pick에서 답이 정답일 때 점수를 1 올리세요- 상단 바의
actions에 테마의titleMedium스타일을 적용해 오른쪽에 16픽셀 여백을 두고 가운데 정렬하여Score: 0(실제 점수 표시)을 보여 주세요
직접 해보기
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;
bool get _isLast => _index == questions.length - 1;
void _pick(int answer) {
if (_answered) return;
setState(() {
_picked = answer;
});
}
void _next() {
setState(() {
_index++;
_picked = null;
});
}
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 ${_index + 1} of ${questions.length}',
style: textTheme.labelLarge,
),
const SizedBox(height: 24),
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]),
),
),
if (_answered && !_isLast)
FilledButton(
onPressed: _next,
child: const Text('Next'),
),
],
),
),
);
}
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
프로젝트의 모든 레슨
직접 연습해 보세요: 온라인 Flutter 컴파일러