dart - Flutter:如何重新运行小部件或构建

标签 dart flutter

我正在尝试创建一个测验应用程序,在我的 playQuiz 中,玩家回答正确答案后将生成新答案。我试图制作一个函数“foo”并调用它,以便它可以更改按钮中的图像和文本。仍然没有任何变化,这只会在我旋转屏幕时发生变化。代码简短易懂。

  class Game extends StatelessWidget {
  final ForceSelection forceSelection;

  Game({Key key, @required this.forceSelection}) : super(key: key);


  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: forceSelection.langSelection, // TODO should work and change later
      theme: new ThemeData(
        primaryColor: Colors.white,
      ),
      home: PlayQuiz(),
    );
  }
}

class PlayQuizState extends State<PlayQuiz> {
  final ForceSelection forceSelection; // TODO Does this get forceSelection

  List<String> groundForce = [ 'sotamies', 'aliupseerioppilas', 'korpraali', 'alikersantti', 'upseerioppilas', 'kersantti', 'upseerikokelas', 'ylikersantti', 'vääpeli', 'ylivääpeli', 'sotilasmestari', 'vänrikki', 'luutnantti', 'yliluutnantti', 'kapteeni', 'majuri', 'everstiluutnantti', 'eversti', 'prikaatikenraali', 'kenraalimajuri', 'kenraaliluutnantti', 'kenraali'];
  List<int> randomList = Helper.randomAnswers();
  static var rng = new Random();
  var corrAnsIndex = rng.nextInt(3);
  int points = 0;
  String quizImage = "";
  String debugText = "";

  PlayQuizState(this.forceSelection); // TODO Does this get langSelection


  void _startGame() {
    quizImage = 'images/' + groundForce[randomList[corrAnsIndex]].replaceAll('ä','a') + '.jpg';
  }
  void _nextGame() {
    setState(() {
        points += 1;
        randomList = Helper.randomAnswers();
        corrAnsIndex = rng.nextInt(3);
        quizImage = 'images/' + groundForce[randomList[corrAnsIndex]].replaceAll('ä','a') + '.jpg';
        debugText = forceSelection.langSelection + randomList.toString() + " " + groundForce[randomList[corrAnsIndex]].replaceAll('ä','a');
        // TODO edited debug text and next is to check if langSelection is fin
    });
  }
  void _endGame() {
    setState(() {
      //TODO Ask for name and send to database
    });
  }
  @override
  Widget build(BuildContext context) {

    _startGame();

    return Scaffold(
      body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Image.asset(quizImage),
              Text("randomList: " + randomList.toString()),
              Text("Oikea vastaus: " +
                  groundForce[randomList[corrAnsIndex]] +
                  " corrAnsIndex: " +
                  corrAnsIndex.toString()),
              Text(debugText + " points: " + points.toString()),
              //Text("Voima valinta: " + forceSelection = Game.forceSelection),
              RaisedButton(
                  child: Text(groundForce[randomList[0]]),
                  onPressed: () {
                    if (0 == corrAnsIndex) {
                      _nextGame();
                      //this.foo();
                    }
                  }),
              RaisedButton(
                  child: Text(groundForce[randomList[1]]),
                  onPressed: () {
                    if (1 == corrAnsIndex) {
                      _nextGame();
                    }
                  }),
              RaisedButton(
                  child: Text(groundForce[randomList[2]]),
                  onPressed: () {
                    if (2 == corrAnsIndex) {
                      _nextGame();
                    }
                  }),
              RaisedButton(
                  child: Text(groundForce[randomList[3]]),
                  onPressed: () {
                    if (3 == corrAnsIndex) {
                      _nextGame();
                    }
                  }),
            ],
          )),
    );
  }

}


class PlayQuiz extends StatefulWidget {
  @override
  PlayQuizState createState() => new PlayQuizState(ForceSelection("","")); //TODO how to pass vars to ""
}

最佳答案

您必须使用 setState 来重建小部件以更新 View ,并将您的小部件更改为 StatefulWidget,而不是 StatelessWidget。

文档:https://docs.flutter.io/flutter/widgets/State/setState.html https://flutterdoc.com/stateful-or-stateless-widgets-42a132e529ed

我建议你应该花更多的时间学习一些 flutter 的基本概念,然后继续你的开发。

关于dart - Flutter:如何重新运行小部件或构建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55487159/

相关文章:

flutter - 从 dart 中的字符串的开头和结尾修剪和删除特定字符

firebase - FLUTTER:如何使用云 Firestore 中的 where 子句删除多个文档?

google-maps - 如何在Dart中的Uri查询字符串中重复键

json - 带有 flutter 的 json_serializable 包的错误状态意外诊断

dart - 为什么*any*在此示例中不回溯?

android - 错误 : E/flutter ( 8247): NoSuchMethodError: The getter 'length' was called on null

flutter - List.map()中的递增计数

firebase - flutter 问题 : type 'Timestamp' is not a subtype of type 'DateTime'

flutter - 未实现的缺失静态目标处理,Flutter

dart - 如何在 Flutter 中使用 SQFlite 更新数据库表