Search code examples
flutterdartmobilestatic

What is the purpose of using 'Static' in this Flutter/Dart code?


My code do not work without 'Static'. What does it do? and why the code don't work without it? Is it simillar or related to initState() Function?

Did a reasearch but Google answers weren't enough. Thanks.

class ResultScreen extends StatelessWidget {
  ResultScreen({super.key});

  static int correctAnswersCount = 0;

  static int correctAnswersCounter() {
    for (int i = 0; i < selectedAnswers.length; i++) {
      if (selectedAnswers[i] == questions[i].answers[0]) {
        correctAnswersCount++;
      }
    }
    return correctAnswersCount;
  }

  static int x = correctAnswersCounter();
  int y = questions.length;

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(mainAxisSize: MainAxisSize.min, children: [
        ResultText('You have answerd $x of $y questions currectly.')
      ]),
    );
  }
}


Solution

  • 'Static' keyword is used to indicate that variable is belongs to a class instead of instance of a class.

    You are getting error because you are trying to access instance variable selectedAnswers and questions from Static method. Dart doesn't know which class they belong to.

    you can pass them like this if you don't want static

    class ResultScreen extends StatelessWidget {
     ResultScreen({super.key});
    
     static int correctAnswersCounter(List<String> questions, List<String> selectedAnswers) {
       int correctAnswersCount = 0;
       for (int i = 0; i < selectedAnswers.length; i++) {
         if (selectedAnswers[i] == questions[i].answers[0]) {
           correctAnswersCount++;
         }
       }
       return correctAnswersCount;
     }
    
     @override
     Widget build(BuildContext context) {
       int x = correctAnswersCounter(questions, selectedAnswers);
       int y = questions.length;
       return Center(
         child: Column(mainAxisSize: MainAxisSize.min, children: [
           ResultText('You have answered $x of $y questions correctly.')
         ]),
       );
     }
    }
    

    this might help you https://www.darttutorial.org/dart-tutorial/dart-static/