Victor Kennedy
Victor Kennedy

Reputation: 139

Flutter: add list item to list containing a map

I am creating a quiz app to practice flutter. I have a list called questions, which contains a map which has 2 different types of data: questionText, correctAnswer. I am trying to create 2 text inputs with a button to create a new question. However, I am receiving an error. Please help.

Would be so thankful if you wanted to help

Error message:

Error message

StatefulWidget file containin function to add question to the list (addNewQuestion)

import 'package:flutter/material.dart';
    import 'questionText.dart';
    import 'buttons.dart';
    import 'end.dart';
    import '../pages/add_questions.dart';
    import '../model/question_class.dart';
    
    class QuizPage extends StatefulWidget {
      @override
      State<QuizPage> createState() => _QuizPageState();
    }
    
    class _QuizPageState extends State<QuizPage> {
      int questionIndex = 0;
      int points = 0;
    
      List<Widget> scoreKeeper = [];
    
      List _questions = [
        {'questionText': 'Victor loves computers', 'correctAnswer': 'true'},
        {'questionText': 'Victor is learning Flutter', 'correctAnswer': 'true'},
        {
          'questionText': 'Victor favorite team is Manchester United',
          'correctAnswer': 'false'
        },
        {'questionText': 'Victor favorite team is Chelsea', 'correctAnswer': 'true'}
      ];
    
      void _addIndex() {
        setState(() {
          questionIndex = questionIndex + 1;
        });
      }
    
      late String userAnswer;
    
      void _setUserAnswerTrue() {
        setState(() {
          userAnswer = 'true';
        });
      }
    
      void _setUserAnswerFalse() {
        setState(() {
          userAnswer = 'false';
        });
      }
    
      void _checkIfCorrect() {
        String correctAnswer =
            _questions[questionIndex]['correctAnswer'].toString();
        setState(() {
          correctAnswer == userAnswer ? points = points + 1 : points = points;
          print(points);
        });
        setState(
          () {
            correctAnswer == userAnswer
                ? scoreKeeper.add(
                    Icon(
                      Icons.check,
                      color: Colors.green,
                    ),
                  )
                : scoreKeeper.add(
                    Icon(
                      Icons.close,
                      color: Colors.red,
                    ),
                  );
          },
        );
      }
    
      void restartQuiz() {
        setState(() {
          questionIndex = 0;
          scoreKeeper.clear();
          points = 0;
        });
      }
    
      void addNewQuestion(String txTitle, String correctBool) {
        final newTx = Question(
          title: txTitle,
          correctAnswer: correctBool,
        );
    
        setState(
          () {
            _questions.add({newTx});
          },
        );
      }
    /*   void addNewBool(bool txAnswer) {
        final newBool = Answer(
          correctAnswer: txAnswer,
        );
        setState(() {
          answers.add(txAnswer);
        });
      } */
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            backgroundColor: Colors.grey.shade900,
            actions: [
              IconButton(
                onPressed: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) => AddQuestions(addNewQuestion),
                    ),
                  );
                },
                icon: Icon(Icons.add),
              ),
            ],
          ),
          backgroundColor: Colors.grey.shade900,
          body: SafeArea(
              child: Padding(
            padding: const EdgeInsets.all(10.0),
            child: questionIndex < _questions.length
                ? Column(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    crossAxisAlignment: CrossAxisAlignment.stretch,
                    children: [
                      QuestionText(_questions, questionIndex),
                      QuButtons(_setUserAnswerTrue, _setUserAnswerFalse,
                          _checkIfCorrect, _addIndex),
                      Padding(
                        padding: const EdgeInsets.symmetric(horizontal: 8.0),
                        child: Row(
                          children: scoreKeeper,
                        ),
                      ),
                    ],
                  )
                : EndOfQuiz(scoreKeeper, restartQuiz, points, _questions.length),
          )),
        );
      }
    }

File containing inputs and buttons to add new question: import 'package:flutter/material.dart'; import '../widgets/quiz_page.dart';

    class AddQuestions extends StatelessWidget {
      final titleController = TextEditingController();
      final answerController = TextEditingController();
      final Function addQu;
      AddQuestions(this.addQu);
    
      void submitInput() {
        final enteredTitle = titleController.text;
        final enteredBool = answerController.text;
    
        addQu(
          enteredTitle,
          enteredBool,
        );
      }
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: Scaffold(
            backgroundColor: Colors.grey.shade900,
            appBar: AppBar(
              backgroundColor: Colors.grey.shade900,
              leading: IconButton(
                icon: Icon(Icons.arrow_back),
                onPressed: () {
                  Navigator.pop(context);
                },
              ),
            ),
            body: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                Padding(
                  padding: const EdgeInsets.all(20),
                  child: TextField(
                    controller: titleController,
                    decoration: InputDecoration(
                      border: OutlineInputBorder(),
                      labelText: 'Question Text',
                    ),
                    onSubmitted: (_) => addQu(),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.all(20),
                  child: TextField(
                    controller: answerController,
                    decoration: InputDecoration(
                      border: OutlineInputBorder(),
                      labelText: 'True/False',
                    ),
                    onSubmitted: (_) => addQu(),
                  ),
                ),
                FlatButton(
                  onPressed: () {
                    addQu();
                  },
                  child: Text('Add button'),
                )
              ],
            ),
          ),
        );
      }
    }

Upvotes: 1

Views: 618

Answers (1)

ישו אוהב אותך
ישו אוהב אותך

Reputation: 29783

Your AddQuestions class need a Function parameters:

class AddQuestions extends StatelessWidget {
  ...
  final Function addQu;
  AddQuestions(this.addQu);

  ...
}

But you're giving Function(String, String) when calling it with:

AddQuestions(addNewQuestion)

where addNewQuestion is:

void addNewQuestion(String txTitle, String correctBool)

So, you need to change AddQuestions parameter to Function(String, String), like this:

class AddQuestions extends StatelessWidget {
  ...
  final Function(String, String) addQu;
  AddQuestions(this.addQu);

  ...
}

Upvotes: 1

Related Questions