【Flutter/Dart】シンプルなクイズアプリを作ってみる

実装

main.dart

import 'package:flutter/material.dart';
import 'quiz_app.dart';

void main() {
  runApp(QuizApp());
}

question.dart

class Question {
  final String questionText;
  final List<Answer> answers;

  Question({
    required this.questionText,
    required this.answers,
  });
}

class Answer {
  final String text;
  final bool isCorrect;

  Answer({
    required this.text,
    required this.isCorrect,
  });
}

quiz_app.dart

import 'package:flutter/material.dart';
import 'quiz_screen.dart'; // Make sure this import is correct.

class QuizApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: QuizScreen(),
    );
  }
}

quiz_card.dart

import 'package:flutter/material.dart';
import 'question.dart';

class QuizCard extends StatelessWidget {
  final String question;
  final List<Answer> answers;
  final Function(bool) onAnswerSelected;

  QuizCard({
    required this.question,
    required this.answers,
    required this.onAnswerSelected,
  });

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Text(
            question,
            textAlign: TextAlign.center,
            style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
          ),
          SizedBox(height: 16),
          ...answers.map((answer) {
            return Padding(
              padding: const EdgeInsets.symmetric(vertical: 8.0),
              child: ElevatedButton(
                onPressed: () => onAnswerSelected(answer.isCorrect),
                style: ElevatedButton.styleFrom(
                  primary: Colors.blue,
                  minimumSize: Size(double.infinity, 48), // Set the height of the button
                ),
                child: Text(answer.text, style: TextStyle(fontSize: 16)),
              ),
            );
          }).toList(),
        ],
      ),
    );
  }
}

quiz_screen.dart

import 'package:flutter/material.dart';
import 'quiz_card.dart';
import 'result.dart';
import 'question.dart'; // Import the Question and Answer classes.

class QuizScreen extends StatefulWidget {
  @override
  _QuizScreenState createState() => _QuizScreenState();
}

class _QuizScreenState extends State<QuizScreen> {
  int _questionIndex = 0;
  int _score = 0;

  List<Question> _questions = [
    Question(
      questionText: 'What is the largest planet in our solar system?',
      answers: [
        Answer(text: 'Mars', isCorrect: false),
        Answer(text: 'Jupiter', isCorrect: true),
        Answer(text: 'Saturn', isCorrect: false),
        Answer(text: 'Neptune', isCorrect: false),
      ],
    ),
    Question(
      questionText: 'Which animal is known as the "King of the Jungle"?',
      answers: [
        Answer(text: 'Elephant', isCorrect: false),
        Answer(text: 'Tiger', isCorrect: false),
        Answer(text: 'Lion', isCorrect: true),
        Answer(text: 'Giraffe', isCorrect: false),
      ],
    ),
    Question(
      questionText: 'What is the chemical symbol for gold?',
      answers: [
        Answer(text: 'Au', isCorrect: true),
        Answer(text: 'Ag', isCorrect: false),
        Answer(text: 'Cu', isCorrect: false),
        Answer(text: 'Fe', isCorrect: false),
      ],
    ),
    Question(
      questionText: 'Which country is famous for the Great Wall?',
      answers: [
        Answer(text: 'India', isCorrect: false),
        Answer(text: 'China', isCorrect: true),
        Answer(text: 'Italy', isCorrect: false),
        Answer(text: 'Brazil', isCorrect: false),
      ],
    ),
    Question(
      questionText: 'What is the primary gas that makes up Earth\'s atmosphere?',
      answers: [
        Answer(text: 'Oxygen', isCorrect: false),
        Answer(text: 'Nitrogen', isCorrect: true),
        Answer(text: 'Carbon dioxide', isCorrect: false),
        Answer(text: 'Helium', isCorrect: false),
      ],
    ),

    // Add more questions here
  ];

  void _answerQuestion(bool isCorrect) {
    setState(() {
      if (isCorrect) {
        _score++;
      }
      _questionIndex++;
    });
  }

  void _resetQuiz() {
    setState(() {
      _questionIndex = 0;
      _score = 0;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Quiz App'),
      ),
      body: _questionIndex < _questions.length
          ? QuizCard(
        question: _questions[_questionIndex].questionText,
        answers: _questions[_questionIndex].answers,
        onAnswerSelected: _answerQuestion,
      )
          : Result(_score, _questions.length, _resetQuiz),
    );
  }
}

result.dart

import 'package:flutter/material.dart';

class Result extends StatelessWidget {
  final int score;
  final int totalQuestions;
  final Function() onRestartQuiz;

  Result(this.score, this.totalQuestions, this.onRestartQuiz);

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text(
            'Your Score: $score / $totalQuestions',
            style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
          ),
          SizedBox(height: 16),
          ElevatedButton(
            onPressed: onRestartQuiz,
            style: ElevatedButton.styleFrom(
              primary: Colors.blue, // Customize button color
              padding: EdgeInsets.symmetric(horizontal: 24, vertical: 12),
            ),
            child: Text('Restart Quiz', style: TextStyle(fontSize: 18)),
          ),
        ],
      ),
    );
  }
}

この記事は役に立ちましたか?

はい
いいえ
貴重なフィードバックありがとうございます!