クイズ:正解か不正解か
CoddyのFlutterジャーニー「プロジェクト」セクションの一部。レッスン 11/36。
解答をタップすると、クイズはすぐに結果を知らせます。正解なら緑、不正解なら赤にし、どちらの場合も正解を緑で表示するので、答えを覚えられます。
状態には、どの解答をタップしたかを記憶させる必要があります。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 のときに実行されます。
チャレンジ
難しい回答に色を付けましょう:
- 理論で説明した
int? _picked、ゲッターの_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),
),
),
],
),
),
);
}
}
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
プロジェクトのすべてのレッスン
自分で練習してみよう: Flutterオンラインコンパイラ