Quiz App Using Provider
Creating a Quiz App Using Provider in Flutter
Building a quiz app in Flutter with Provider involves managing the quiz state, including questions, answers, and user scores. This tutorial will guide you through creating a simple quiz app using Provider for state management.
Step 1: Setup Provider
First, ensure the Provider package is included in your pubspec.yaml
file:
dependencies:
flutter:
sdk: flutter
provider: ^5.0.0
Step 2: Define the Quiz Model
Create a model to represent your quiz. It should include questions, options, and the logic to check answers and track scores.
class Quiz with ChangeNotifier {
final List<Map<String, dynamic>> _questions = [
{
'questionText': 'What is Flutter?',
'answers': [
{'text': 'A programming language', 'score': 0},
{'text': 'A web framework', 'score': 0},
{'text': 'A mobile UI framework', 'score': 1},
{'text': 'A game', 'score': 0},
],
},
{
'questionText': 'What language is Flutter written in?',
'answers': [
{'text': 'Dart', 'score': 1},
{'text': 'Java', 'score': 0},
{'text': 'Kotlin', 'score': 0},
{'text': 'Swift', 'score': 0},
],
},
// Add more questions here
];
int _questionIndex = 0;
int _totalScore = 0;
void answerQuestion(int score) {
_totalScore += score;
_questionIndex++;
notifyListeners();
}
int get questionIndex => _questionIndex;
int get totalScore => _totalScore;
List<Map<String, dynamic>> get questions => _questions;
bool get isQuizFinished => _questionIndex >= _questions.length;
void resetQuiz() {
_questionIndex = 0;
_totalScore = 0;
notifyListeners();
}
}
Step 3: Setup Provider in Main
Wrap your app with ChangeNotifierProvider
to provide the quiz model.
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'quiz.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (ctx) => Quiz(),
child: MaterialApp(
home: QuizPage(),
),
);
}
}
Step 4: Build the Quiz UI
Create a widget to display the quiz question and options. Use Provider.of
to access and display quiz data, and to handle answer selection.
class QuizPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
var quiz = Provider.of<Quiz>(context);
return Scaffold(
appBar: AppBar(title: Text('Quiz App')),
body: quiz.isQuizFinished
? Center(
child: Text('Your score: ${quiz.totalScore}'),
)
: Column(
children: <Widget>[
Text(quiz.questions[quiz.questionIndex]['questionText']),
...(quiz.questions[quiz.questionIndex]['answers'] as List<Map<String, dynamic>>)
.map((answer) => ElevatedButton(
onPressed: () => quiz.answerQuestion(answer['score']),
child: Text(answer['text']),
))
.toList(),
],
),
floatingActionButton: FloatingActionButton(
onPressed: quiz.resetQuiz,
child: Icon(Icons.refresh),
),
);
}
}