【maaath】 Flutter for OpenHarmony足球计时应用开发实战

张开发
2026/5/10 23:52:50 15 分钟阅读

分享文章

【maaath】 Flutter for OpenHarmony足球计时应用开发实战
Flutter 足球计时应用在 OpenHarmony 上的开发实战欢迎加入开源鸿蒙跨平台社区https://openharmonycrossplatform.csdn.net作者maaath一、引言随着 OpenHarmony 生态的快速发展Flutter 作为优秀的跨平台框架在鸿蒙设备上的适配日趋成熟。本文将带领读者从零构建一个功能完整的足球计时应用涵盖比赛计时、进球统计、红黄牌管理、换人管理、数据导出、球队阵容管理、新闻资讯、直播提醒和社区讨论等九大功能模块。所有代码均已在 OpenHarmony 设备上验证通过可直接运行。项目完整代码已托管至 AtomGit 平台https://atomgit.com欢迎访问获取源码。二、应用架构设计在开始编码之前我们先梳理应用的架构。整个应用采用分层设计数据模型层Models定义球员、球队、比赛事件、新闻、提醒、帖子等数据结构业务服务层Services封装比赛逻辑、球队管理、新闻数据、提醒管理、社区交互等核心业务页面展示层Pages提供用户交互界面包含 8 个功能页面这种分层架构的好处是职责清晰、易于扩展。当需要增加新功能时只需在对应层添加代码即可不会影响现有逻辑。三、数据模型层实现数据模型是应用的基石。我们先定义球员模型它包含了球员的基本信息和比赛状态classFootballPlayer{finalStringid;finalStringname;finalint number;finalStringposition;finalStringteamId;bool isOnField;int goals;int yellowCards;bool redCard;FootballPlayer({requiredthis.id,requiredthis.name,requiredthis.number,requiredthis.position,requiredthis.teamId,this.isOnFieldtrue,this.goals0,this.yellowCards0,this.redCardfalse,});StringgetpositionName{switch(position){caseGK:return门将;caseCB:return中后卫;caseCM:return中场;caseST:return前锋;default:returnposition;}}}接下来是比赛事件模型它记录了比赛中发生的每一个关键事件enumFootballEventType{goal,ownGoal,penaltyGoal,yellowCard,redCard,secondYellowCard,substitution,penaltyMiss,}classFootballEvent{finalStringid;finalStringmatchId;finalFootballEventTypetype;finalint minute;finalStringplayerId;finalStringplayerName;finalint playerNumber;finalStringteamId;finalString?assistPlayerName;finalString?substitutePlayerName;Stringgetdescription{switch(type){caseFootballEventType.goal:returnassistPlayerName!null?$playerName进球 (助攻:$assistPlayerName):$playerName进球;caseFootballEventType.yellowCard:return$playerName黄牌警告;caseFootballEventType.redCard:return$playerName红牌罚下;caseFootballEventType.substitution:return$playerName↓$substitutePlayerName↑;default:returntypeName;}}}比赛模型是整个应用的核心它管理着比赛的状态、计时和比分enumMatchStatus{notStarted,firstHalf,halfTime,secondHalf,finished}classFootballMatch{finalStringid;finalFootballTeamhomeTeam;finalFootballTeamawayTeam;int homeScore;int awayScore;MatchStatusstatus;int elapsedSeconds;ListFootballEventevents;StringgetelapsedTime{finalminuteselapsedSeconds~/60;finalsecondselapsedSeconds%60;return${minutes.toString().padLeft(2, 0)}:${seconds.toString().padLeft(2, 0)};}}四、核心业务服务层比赛计时服务是整个应用的大脑。它使用Timer.periodic实现每秒计时并自动处理上下半场切换classFootballMatchService{staticfinalFootballMatchService_instanceFootballMatchService._();factoryFootballMatchService()_instance;FootballMatchService._();final_teamServiceFootballTeamService();FootballMatch?currentMatch;Timer?_timer;voidstartMatch(){currentMatchcurrentMatch!.copyWith(status:MatchStatus.firstHalf,startTime:DateTime.now(),);_startTimer();}void_startTimer(){_timerTimer.periodic(constDuration(seconds:1),(_){if(currentMatchnull)return;currentMatchcurrentMatch!.copyWith(elapsedSeconds:currentMatch!.elapsedSeconds1,);// 自动检测半场结束if(currentMatch!.elapsedSeconds45*60currentMatch!.statusMatchStatus.firstHalf){pauseMatch();currentMatchcurrentMatch!.copyWith(status:MatchStatus.halfTime);}});}voidaddGoal(StringteamId,StringplayerId){// 创建进球事件更新比分和球员进球数finaleventFootballEvent(id:E${_eventIdCounter},matchId:currentMatch!.id,type:FootballEventType.goal,minute:currentMatch!.elapsedSeconds~/60,playerId:playerId,playerName:player.name,playerNumber:player.number,teamId:teamId,);currentMatchcurrentMatch!.copyWith(homeScore:teamIdcurrentMatch!.homeTeam.id?currentMatch!.homeScore1:currentMatch!.homeScore,awayScore:teamIdcurrentMatch!.awayTeam.id?currentMatch!.awayScore1:currentMatch!.awayScore,events:[...currentMatch!.events,event],);}}这里使用了单例模式确保全局只有一个比赛实例。Timer.periodic每秒触发一次更新elapsedSeconds当达到 45 分钟2700秒时自动暂停并切换到中场休息状态。红黄牌管理逻辑中我们特别处理了两黄变一红的规则voidaddYellowCard(StringteamId,StringplayerId){finalplayerteam.players.firstWhere((p)p.idplayerId);finalisSecondYellowplayer.yellowCards1;if(isSecondYellow){// 两黄变一红罚下场_teamService.updatePlayer(teamId,player.copyWith(yellowCards:player.yellowCards1,redCard:true,isOnField:false,));}else{_teamService.updatePlayer(teamId,player.copyWith(yellowCards:player.yellowCards1,));}}五、页面展示层实现比赛计时页面是用户最常使用的界面。它包含比分看板、计时器、控制按钮和事件列表Widget_buildScoreBoard(FootballMatchmatch){returnContainer(padding:constEdgeInsets.all(20),decoration:BoxDecoration(gradient:LinearGradient(colors:[Colors.green.shade800,Colors.green.shade600],),),child:Column(children:[Text(match.statusName,style:TextStyle(color:Colors.white.withValues(alpha:0.8))),Text(match.elapsedTime,style:constTextStyle(color:Colors.white,fontSize:48,fontWeight:FontWeight.bold)),Row(mainAxisAlignment:MainAxisAlignment.spaceEvenly,children:[_buildTeamScore(match.homeTeam,match.homeScore),constText(VS,style:TextStyle(color:Colors.white)),_buildTeamScore(match.awayTeam,match.awayScore),],),],),);}进球记录页面展示了完整的比赛统计信息包括射手榜Widget_buildScorerRow(team){finalscorersteam.players.where((p)p.goals0).toList()..sort((a,b)b.goals.compareTo(a.goals));returnColumn(children:scorers.map((p)Padding(padding:constEdgeInsets.only(left:28,top:4),child:Row(children:[Text(${p.number}),constSizedBox(width:8),Text(p.name),constSpacer(),Row(children:List.generate(p.goals,(i)Icon(Icons.sports_soccer,size:14,color:Colors.orange),),),],),)).toList(),);}六、在 OpenHarmony 上运行要将此应用运行在鸿蒙设备上需要完成以下步骤环境准备安装 DevEco Studio 和 Flutter for OpenHarmony SDK项目配置在ohos目录下配置module.json5确保权限声明正确构建部署使用flutter build ohos命令构建 HAP 包安装运行通过 DevEco Studio 或 hdc 工具安装到鸿蒙设备七、运行截图以下为应用在 OpenHarmony 设备上的运行效果截图截图一足球首页展示应用主界面包含快捷操作入口和功能网格用户可快速进入比赛计时、进球统计、红黄牌管理等模块。截图二比赛计时界面展示比赛进行中的实时比分看板包含主客队名称、比分、比赛时间和事件记录列表。截图三球队阵容管理展示预设的四支球队皇马、巴萨、曼城、拜仁的完整阵容包含首发和替补球员信息。截图六新闻资讯与社区讨论展示足球新闻列表和社区讨论帖子支持点赞互动和发布新帖。八、总结与展望本文详细介绍了如何使用 Flutter for OpenHarmony 开发一个功能完整的足球计时应用。从数据模型设计到业务逻辑实现再到页面展示完整地展示了跨平台应用开发的流程。通过这个项目我们可以看到 Flutter 在 OpenHarmony 上的表现已经非常成熟。无论是计时器的精度、UI 的流畅度还是事件处理的响应速度都能满足实际使用需求。未来可以进一步扩展的功能包括接入实时比赛数据 API获取真实比赛信息添加本地数据库存储持久化比赛历史记录集成推送服务实现比赛开始前的自动提醒支持多语言国际化欢迎访问 AtomGithttps://atomgit.com获取完整源码也欢迎加入开源鸿蒙跨平台社区https://openharmonycrossplatform.csdn.net交流讨论共同推动 Flutter for OpenHarmony 生态发展。

更多文章