【问题标题】:SetState on my overlay blinking the whole game on Flame我的叠加层上的 SetState 在 Flame 上闪烁整个游戏
【发布时间】:2021-09-29 13:31:01
【问题描述】:

我刚刚从 Flame 1.0.0-rc8 更新到 Flame 1.0.0-releasecandidate.14,但现在我的叠加层(菜单、分数等)无法在不闪烁游戏的情况下刷新。

这是我的代码简历:

class _Boat extends State<Boat> with WidgetsBindingObserver {
  BoatGame game;


  @override
  void initState() {
    game = new BoatGame();
    refreshScore();
  }

  refreshScore() async {
    timer = Timer.periodic(Duration(milliseconds: 300), (timer) {
      if (mounted) {
        if (game != null) {
          score = game.getScore();
          setState(() {});
        }
      }
    });
  }


  @override
  Widget build(BuildContext context) {
    Stack(
      children: [
      GameWidget(game: game,),
      Text("My Score: $score");
    ],
  }
}

因此,每 300 毫秒,我的屏幕会闪烁一次,如果我删除 SetState,则不会刷新分数。

解决办法是什么?谢谢

【问题讨论】:

  • 我不知道 Flame,但您是否考虑过使用 ValueNotifier 而不是使用 setState 更新您的小部件?它会有所帮助,因为只有保存分数的 Text 小部件会被更新。

标签: flutter flame


【解决方案1】:

尝试像这样使用 refreshScore() :

 refreshScore() async {
timer = Timer.periodic(Duration(milliseconds: 300), (timer) {
  if (mounted) {
    if (game != null) {
      setState(() {
      score = game.getScore();
       });
    }
  }
});
}

然后 setState 将重建专注于您的分数的状态。

希望我能帮上忙:)

【讨论】:

  • 我看不出你的代码和我的代码有什么区别:/
  • 很抱歉,我没有更改代码,只是解释了我认为可行的方法。现在它已经修复了。再次抱歉
  • NP,我之前已经尝试过您的新代码,但 ValueNotifier 解决方案似乎正在工作:)
  • @LuanSilva 有没有一种有效的方法来调用setState 而无需每 300 毫秒触发一次?
猜你喜欢
  • 2021-02-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-25
  • 2012-05-30
  • 2014-08-10
  • 1970-01-01
相关资源
最近更新 更多