Basic Flutter Quiz : Unable to add Score Mapped from Array

Viewed 29

Im looking for some help with my code, this is for a quiz which adds the score value based on the answers the user selects and outputs a response. Im having issues adding the count. I had followed a youtube tutorial that has some outdated features and I suspect the issues are with the answerQuestion function. How can I pass a value for the total count? I Bolded the area in my main where I suspect I need to push the count value into.

  • When I write the value 2 instead of _totalScore in my Main(I bolded the line) It adds the two.

A similar basic quiz code can be seen here : https://www.geeksforgeeks.org/basic-quiz-app-in-flutter-api/

// Main

``import 'package:flutter/material.dart';
import 'package:flutter_course_guide/result.dart';
import './quiz.dart';
import './result.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    // throw UnimplementedError();
    return _MyAppState();
  }
}

class _MyAppState extends State<MyApp> {
  bool endScreen = true;
  int _totalScore = 0;
  var _bodyScore = 0;
  var _questionIndex = 0;

  final _questions = const [
    {
      'questionText':
          'Hey Name, nice to meet you! Im going to ask you a couple questions to help create your smart workout plan. The first is what is your body type',
      'answers': [
        {
          'text': 'Beginner',
          'desc':
              'first time user, have no or little experience. show me what to do and how to do it',
          'score': 21
        },
        {
          'text': 'Intermediate',
          'desc':
              'I have some exercise experience and how to do them properly. Help me get into a structured routine',
          'score': 1
        },
        {
          'text': 'Advanced',
          'desc': 'Im very experience with training. show me something new',
          'score': 11
        },
      ]
    },
    {
      'questionText':
          'No problem Name, I will create TYPE program for you. What is your main reason for using lift buddy',
      'answers': [
        {
          'text': 'Naturally Skinny',
          'desc': 'I find it harder to add weight/muscle',
          'score': 55
        },
        {
          'text': 'Naturally Muscular',
          'desc': 'I find it harder to add weight/muscle',
          'score': 33
        },
        {
          'text': 'Naturally Higher Body fat',
          'desc': 'i naturally build and athletic',
          'score': 3
        },
      ]
    },
    {
      'questionText': 'random Question',
      'answers': [
        {
          'text': 'Naturally Skinny',
          'desc': 'I find it harder to add weight/muscle',
          'score': 55
        },
        {
          'text': 'Naturally Muscular',
          'desc': 'I find it harder to add weight/muscle',
          'score': 33
        },
        {
          'text': 'Naturally Higher Body fat',
          'desc': 'i naturally build and athletic',
          'score': 3
        },
      ]
    },
    {
      'questionText': 'Whos your fav instructor',
      'answers': [
        {
          'text': 'Naturally Skinny',
          'desc': 'I find it harder to add weight/muscle',
          'score': 10
        },
        {
          'text': 'Naturally Muscular',
          'desc': 'I find it harder to add weight/muscle',
          'score': 5
        },
        {
          'text': 'Naturally Higher Body fat ',
          'desc': 'i naturally build and athletic',
          'score': 3
        },
      ]
    },
  ];

  var counterIndex = 0;
  void counter(int x) {
    setState(() {
      counterIndex = counterIndex + x;
    });
  }


  void _resetQuiz() {
    setState(() {
      _questionIndex = 0;
      // _totalScore = 0;
    });
  }

  void _answerQuestion(int score) {
    // var aBool = true;
    _totalScore = _totalScore + score;
    print('total score :  ${_totalScore}, Body Score: ${score}  ');

    // _bodyScore += bodyScores;

    setState(() {
      if (_questionIndex < _questions.length) {
        _questionIndex++;
      } else {
        print('Were done');

        endScreen = false;
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Lift Buddy'),
        ),
        body: _questionIndex < _questions.length
            ? Quiz(
                answerQuestion: () => _answerQuestion(
                    _totalScore), **// Problem Because its calling function instead of pointing**
                questionIndex: _questionIndex,
                questions: _questions,
              )
            : Result(_totalScore, _resetQuiz),
      ),
    );
  }
}

// Quiz

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

import './question.dart';
import './answer.dart';

class Quiz extends StatelessWidget {
  // final Function answerQuestion;
  final VoidCallback answerQuestion;

  final List<Map<String, Object>> questions;
  final int questionIndex;
  Quiz({
    required this.answerQuestion,
    required this.questions,
    required this.questionIndex,
  });

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Question(
          questions[questionIndex]['questionText'] as String,
        ),
        ...(questions[questionIndex]['answers'] as List<Map<String, Object>>)
            .map((answers) {
          var answerMap = answers as Map<String, Object>;
          var scoreMap = answers as Map<dynamic, dynamic>;

          return Answer(
            answerQuestion,
            answerMap['text'] as String,
            answerMap['desc'] as String,
            scoreMap['score'] as int,
          );
        }).toList()
      ],
    );
  }
}`

// Result

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

class Result extends StatelessWidget {
  final int resultScore;
  // final int bodyScore;
  final VoidCallback resetHandler;

  // Result(this.resultScore, this.bodyScore, this.resetHandler);
  Result(this.resultScore, this.resetHandler);

  String get resultPhrase {
    String resultText;
    // print("resylt score" + resultScore as String);

    if (resultScore <= 8) {
      resultText = 'You are awesome and innocent! ${resultScore}, ';
    } else if (resultScore <= 12) {
      resultText = 'Pretty Likeable! ${resultScore}, ';
    } else if (resultScore <= 16) {
      resultText = 'You are ... strange?!  ${resultScore}, ';
    } else {
      resultText = 'You are so Bad! ${resultScore}, ';
    }
    return resultText;
  }

  @override
  Widget build(BuildContext context) {
    return Center(
        child: Column(
      children: <Widget>[
        Text(
          resultPhrase,
          style: TextStyle(fontSize: 36, fontWeight: FontWeight.bold),
          textAlign: TextAlign.center,
        ),
        RaisedButton(
            child: Text('Restart Quiz!'),
            onPressed: resetHandler,
            textColor: Colors.blue),
      ],
    ));
  }
}`

// Answer

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

class Answer extends StatelessWidget {
  // const answer({ Key? key }) : super(key: key);
  final VoidCallback selectHandler;
  final String answerText;
  final String answerDesc;
  final int scoreCheck;
  // final int bodyScore;

  // Answer(this.selectHandler, this.answerText, this.answerDesc, this.scoreCheck,
  //     this.bodyScore);
  Answer(
    this.selectHandler,
    this.answerText,
    this.answerDesc,
    this.scoreCheck,
  );

  @override
  Widget build(BuildContext context) {
    return OutlinedButton(
      style: OutlinedButton.styleFrom(
        primary: Colors.white,

        tapTargetSize: MaterialTapTargetSize.shrinkWrap,
        // minimumSize: const Size(100, 50),
        // maximumSize: const Size(200, 50),
        backgroundColor: Colors.teal,
        shadowColor: Colors.red,
        elevation: 10,
        // padding: const EdgeInsets.only(top: 10.0, bottom: 10.0),
        padding: const EdgeInsets.all(10.10),
        alignment: Alignment.center,
        shape: const RoundedRectangleBorder(
            borderRadius: BorderRadius.all(Radius.circular(4))),
      ),
      onPressed: selectHandler,
      child: Column(
        mainAxisSize: MainAxisSize.max,
        // mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        mainAxisAlignment: MainAxisAlignment.spaceAround,

        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Align(
            alignment: Alignment.center,
          ),
          Text(answerText,
              style: TextStyle(fontSize: 16.0, fontWeight: FontWeight.bold),
              textAlign: TextAlign.center),
          // give it width

          Text(answerDesc,
              style: TextStyle(fontSize: 10.0), textAlign: TextAlign.center),
          Text("${scoreCheck}",
              style: TextStyle(fontSize: 16.0, fontWeight: FontWeight.bold),
              textAlign: TextAlign.center),
          // Spacer(),
          // SizedBox(height: 50),
        ],
      ),
    );
  }
}`

// Question

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

class Question extends StatelessWidget {
  // const Question({Key? key}) : super(key: key);
  final String questionText;
  Question(this.questionText);
  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      margin: EdgeInsets.all(10),
      child: Text(
        questionText,
        style: TextStyle(
          fontSize: 18,
        ),
        textAlign: TextAlign.center,
      ),
    );
  }
}`
1 Answers

I solved this issue by changing the callback function in the main

answerQuestion: () => _answerQuestion,

Changed the parameter in Quiz.dart

answerQuestion: (int input) => _answerQuestion(input),

Passing the score as int in Answer widget

return Answer(
  () => answerQuestion(answer['score'] as int),
 
); 
Related