在此 Flutter/Dart 代码中使用“静态”的目的是什么?

问题描述 投票:0回答:1

如果没有“静态”,我的代码将无法工作。它有什么作用?为什么没有它代码就无法工作? 与 initState() 函数类似或相关吗?

做了研究,但谷歌的答案还不够。谢谢。

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.')
      ]),
    );
  }
}

flutter dart mobile static
1个回答
0
投票

“Static”关键字用于指示变量属于类而不是类的实例。

您收到错误,因为您试图从静态方法访问实例变量

selectedAnswers
questions
。 Dart 不知道它们属于哪个类。

如果你不想静态,你可以这样传递它们

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.')
     ]),
   );
 }
}

这可能对您有帮助https://www.darttutorial.org/dart-tutorial/dart-static/

© www.soinside.com 2019 - 2024. All rights reserved.