当前位置: 首页 > news >正文

Flutter MVC架构详解:经典架构模式实战

Flutter MVC架构详解经典架构模式实战一、MVC概述MVCModel-View-Controller是一种经典的软件架构模式将应用分为三个主要部分。1.1 组件职责组件职责Model数据和业务逻辑View用户界面展示Controller处理用户交互二、实现MVC2.1 Model层class User { final int id; final String name; final String email; User({required this.id, required this.name, required this.email}); factory User.fromJson(MapString, dynamic json) { return User( id: json[id], name: json[name], email: json[email], ); } MapString, dynamic toJson() { return { id: id, name: name, email: email, }; } } class UserRepository { FutureUser getUser(int id) async { // 模拟API调用 await Future.delayed(const Duration(seconds: 1)); return User(id: id, name: John Doe, email: johnexample.com); } }2.2 Controller层class UserController { final UserRepository _repository; User? _user; bool _isLoading false; String? _error; UserController(this._repository); User? get user _user; bool get isLoading _isLoading; String? get error _error; Futurevoid fetchUser(int id) async { _isLoading true; _error null; notifyListeners(); try { _user await _repository.getUser(id); } catch (e) { _error e.toString(); } finally { _isLoading false; notifyListeners(); } } // 通知机制可以使用ChangeNotifier或自定义 void notifyListeners() {} }2.3 View层class UserView extends StatelessWidget { final UserController controller; const UserView({super.key, required this.controller}); override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text(User Profile)), body: controller.isLoading ? const Center(child: CircularProgressIndicator()) : controller.error ! null ? Center(child: Text(Error: ${controller.error})) : controller.user ! null ? UserProfile(user: controller.user!) : const Center(child: Text(No user data)), ); } } class UserProfile extends StatelessWidget { final User user; const UserProfile({super.key, required this.user}); override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.all(16), child: Column( children: [ const CircleAvatar(radius: 40), const SizedBox(height: 16), Text(user.name, style: const TextStyle(fontSize: 24, fontWeight: FontWeight.bold)), Text(user.email, style: const TextStyle(color: Colors.grey)), ], ), ); } }三、使用ChangeNotifierimport package:flutter/foundation.dart; class UserController extends ChangeNotifier { final UserRepository _repository; User? _user; bool _isLoading false; String? _error; UserController(this._repository); User? get user _user; bool get isLoading _isLoading; String? get error _error; Futurevoid fetchUser(int id) async { _isLoading true; _error null; notifyListeners(); try { _user await _repository.getUser(id); } catch (e) { _error e.toString(); } finally { _isLoading false; notifyListeners(); } } } // 使用 class UserPage extends StatelessWidget { const UserPage({super.key}); override Widget build(BuildContext context) { return ChangeNotifierProvider( create: (context) UserController(UserRepository()), child: const UserView(), ); } } class UserView extends ConsumerUserController { const UserView({super.key}); override Widget build(BuildContext context, WidgetRef ref) { final controller ref.watch(userControllerProvider); return Scaffold( appBar: AppBar(title: const Text(User)), body: controller.isLoading ? const CircularProgressIndicator() : UserProfile(user: controller.user!), floatingActionButton: FloatingActionButton( onPressed: () controller.fetchUser(1), child: const Icon(Icons.refresh), ), ); } }四、项目结构lib/ models/ user.dart repositories/ user_repository.dart controllers/ user_controller.dart views/ user_page.dart user_profile.dart main.dart五、MVC与其他架构对比架构优点缺点MVC简单直观职责分明View和Controller耦合MVP解耦View和ModelPresenter代码量大MVVM数据绑定可测试性好学习曲线较陡Clean Architecture高度解耦易维护结构复杂总结MVC是一种经典的架构模式适合中小型Flutter应用。关键要点Model数据模型和业务逻辑ViewUI展示不包含业务逻辑Controller处理用户交互更新ModelChangeNotifier实现状态通知机制Provider管理Controller生命周期通过合理使用MVC你可以构建结构清晰、易于维护的Flutter应用。
http://www.gsyq.cn/news/1397402.html

相关文章:

  • 告别DOS!2024年Windows下硬盘健康检查,这3款工具最省心(附DiskGenius详细操作)
  • 降AI率天花板!AI率92%暴降至5%!实测10款降AI率软件!薅羊毛技巧!
  • AI学习——Agent 基础概念
  • 【限时稀缺】OpenAI教育计划剩余配额告急!全国高校学生剩余免费额度实时监测(附抢注倒计时)
  • 独家拆解2026年Top 5 AI工具底层架构(含LLM Runtime兼容性报告):为什么92%的技术选型会误判编排层风险?
  • 奶牛发情体征及行为智能检测技术【附算法】
  • LyricsX桌面歌词插件实战指南:打造专属的macOS音乐体验
  • FreeRADIUS 802.1x从零配置实战:EAP-TLS证书链与五层排错
  • Ollama Python SDK工程实践:本地大模型服务化开发指南
  • 工业AOI实战:如何将HRIPCB数据集与YOLOv8结合,打造你自己的PCB缺陷检测系统
  • 5分钟掌握Ofd2Pdf:免费开源OFD转PDF工具终极指南
  • 从BCI Competition IV 2a数据集的.mat文件里,我们能挖出哪些宝藏信息?
  • 空间相关信道下大规模MIMO球面解码器算法与硬件架构优化
  • 现在不重构Lovable体育平台的API网关,Q3将面临3类监管处罚风险:OpenAPI 3.1合规改造倒计时
  • 2026年 徐州/江苏木门与全屋定制厂家推荐榜:实木门、复合门、烤漆门及门墙柜同色一体化优质品牌解析 - 品牌企业推荐师(官方)
  • CPT Markets:从技术架构看平台运行稳定性
  • Cadence Concept HDL 17.4 保姆级开箱指南:从零新建你的第一个工程
  • 【限时解密】Lovable内部未公开的Audit-Trace关联引擎白皮书(仅开放72小时):实现用户行为→API调用→数据库变更→网络流量的端到端溯源
  • 留学生论文被判 AI 生成?PaperXie 帮你轻松通过 Turnitin AIGC 检测
  • 基于混合Transformer的稀疏多通道sEMG手势识别模型TraHGR详解
  • Agent 一接思维导图就开始分支错位:从 Node Binding 到 Hierarchy Commit 的工程实战
  • HSGA模型:基于自引导注意力机制从临床文本预测疾病风险
  • 别再熬夜改答辩 PPT 了!Okbiye AI PPT 一键搞定,模板直接用到爽
  • 拒绝答非所问:手把手教你管理OpenClow的记忆体(Context-7实战与记忆压缩)
  • 2026年5月成都企业GEO优化外包公司怎么选择? - TOP10品牌推荐榜单
  • Go语言数据导出:Excel与CSV
  • 基于文本诱导与图素训练的低资源语言TTS语言适应框架
  • Ubuntu系统中telnet服务的配置与安全实践
  • B站视频转换终极指南:m4s格式快速转为MP4的完整解决方案
  • [智能体-100]:采样策略深度详解:temperature /top_p/top_k