Menu
CoddyTech

クイズ:問題

CoddyのFlutterジャーニー「プロジェクト」セクションの一部。レッスン 10/36。

2つ目のアプリは、Flutterそのものに関するクイズです。問題、タップして選ぶ4つの回答、正解なら緑、不正解なら赤で表示される色、得点、そして結果画面があります。

問題はスターターにすでに用意されています。それぞれが、問題文、4つの回答、正解の位置を持つQuestionです。

Question('Which language do you write Flutter apps in?',
    ['Kotlin', 'Swift', 'Dart', 'JavaScript'], 2),

位置は0から始まるので、2は'Dart'です。状態は、現在の問題を示す_indexを保持し、questions[_index]がその問題です。

回答は、Columnの中にあるforによるコレクションです。回答ごとにボタンが1つあります。FilledButton.tonalはテーマの色で塗りつぶされた控えめなボタンで、選択肢の一覧に適しています。crossAxisAlignment: CrossAxisAlignment.stretchを指定すると、Columnは各子要素の幅を自身と同じにするため、4つのボタンが端から端まで揃います。

challenge icon

チャレンジ

簡単

最初の質問を表示します。

  • 状態に int _index = 0; を追加します
  • Center を、24ピクセルのパディングを設けて子要素を横方向いっぱいに広げる Column に置き換えます
  • その中に、テーマの headlineSmall スタイルで質問文を表示し、24ピクセルの間隔を空けた後、各回答に対して FilledButton.tonal を配置します。ボタンの内側には16ピクセルのパディングを設け、それぞれの下には12ピクセルの間隔を空けます

自分で試してみよう

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> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Flutter Quiz')),
      body: const Center(
        child: Text('Your quiz goes here'),
      ),
    );
  }
}
quiz icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

プロジェクトのすべてのレッスン

自分で練習してみよう: Flutterオンラインコンパイラ