ivsongborges

Untitled

Oct 6th, 2020 (edited)
504
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Dart 1.35 KB | None | 0 0
  1. import 'dart:math';
  2. import 'package:flutter_app/models/question.dart';
  3. import 'package:flutter_app/services/quiz_api.dart';
  4.  
  5. class QuizController {
  6.   List<Question> _questionBank;
  7.  
  8.   Random _random = new Random();
  9.   int questionIndex = 0;
  10.   bool _shiftAnswer;
  11.   int hitNumber = 0;
  12.  
  13.   int get questionsNumber => _questionBank.length ?? 0;
  14.   Question get question => _questionBank[questionIndex];
  15.  
  16.   Future<void> initialize() async {
  17.     questionIndex = 0;
  18.     hitNumber = 0;
  19.     _questionBank = await QuizApi.fetch();
  20.     print('Number of questions: ${_questionBank.length}');
  21.     _questionBank.shuffle();
  22.     _shiftAnswer = _random.nextBool();
  23.   }
  24.  
  25.   void nextQuestion() {
  26.     questionIndex = ++questionIndex % _questionBank.length;
  27.     _shiftAnswer = _random.nextBool();
  28.   }
  29.  
  30.   String getQuestion() {
  31.     return _questionBank[questionIndex].question;
  32.   }
  33.  
  34.   String getAnswer1() {
  35.     return _shiftAnswer
  36.         ? _questionBank[questionIndex].answer1
  37.         : _questionBank[questionIndex].answer2;
  38.   }
  39.  
  40.   String getAnswer2() {
  41.     return _shiftAnswer
  42.         ? _questionBank[questionIndex].answer2
  43.         : _questionBank[questionIndex].answer1;
  44.   }
  45.  
  46.   bool correctAnswer(String answer) {
  47.     var correct = _questionBank[questionIndex].answer1 == answer;
  48.     hitNumber = hitNumber + (correct ? 1 : 0);
  49.     return correct;
  50.   }
  51. }
Add Comment
Please, Sign In to add comment