Flame游戏Flutter中TimerComponent添加if语句报错及取消定时器方法
问题解决方案
一、修复if语句的"Expected an identifier"错误
错误根源有两点:
- 箭头函数
() =>仅支持单个表达式,不能直接嵌套if语句块,需改用普通函数体的大括号写法。 - 你已初始化
instructions = [],该变量永远不会为null,instructions != null的判断无效,应检查列表是否非空。
修改后的代码:
var instructions = []; void myGame() { add( TimerComponent(period: 2, repeat: true, onTick: () { if (instructions.isNotEmpty) { // 用isNotEmpty判断列表非空 populateInfo(instructions); } }), ); }
二、取消定时器的方法
要取消TimerComponent,需先保存它的实例,后续调用cancel()方法即可:
var instructions = []; TimerComponent? myTimer; // 声明变量存储定时器实例 void myGame() { myTimer = TimerComponent(period: 2, repeat: true, onTick: () { if (instructions.isNotEmpty) { populateInfo(instructions); } }); add(myTimer!); } // 调用此函数即可取消定时器 void cancelTimer() { myTimer?.cancel(); myTimer = null; // 可选:清空变量避免潜在内存泄漏 }
内容的提问来源于stack exchange,提问作者czygx
相关产品推荐
相关产品推荐

