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

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

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

一、MVC概述

MVC(Model-View-Controller)是一种经典的软件架构模式,将应用分为三个主要部分。

1.1 组件职责

组件职责
Model数据和业务逻辑
View用户界面展示
Controller处理用户交互

二、实现MVC

2.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(Map<String, dynamic> json) { return User( id: json['id'], name: json['name'], email: json['email'], ); } Map<String, dynamic> toJson() { return { 'id': id, 'name': name, 'email': email, }; } } class UserRepository { Future<User> getUser(int id) async { // 模拟API调用 await Future.delayed(const Duration(seconds: 1)); return User(id: id, name: 'John Doe', email: 'john@example.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; Future<void> 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)), ], ), ); } }

三、使用ChangeNotifier

import '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; Future<void> 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 Consumer<UserController> { 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应用。

关键要点:

  1. Model:数据模型和业务逻辑
  2. View:UI展示,不包含业务逻辑
  3. Controller:处理用户交互,更新Model
  4. ChangeNotifier:实现状态通知机制
  5. Provider:管理Controller生命周期

通过合理使用MVC,你可以构建结构清晰、易于维护的Flutter应用。

http://www.jsqmd.com/news/893548/

相关文章:

  • 2026西南方管供应商推荐及选购指南:镀锌方管生产厂家/附近方管批发/附近钢材批发市场/附近钢材采购批发/哪里有方管批发/选择指南 - 优质品牌商家
  • Ollama Python SDK工程实践:本地大模型服务化开发指南
  • Animotion MCP:基于MCP协议为AI编程提供标准图标与动画资源
  • 深圳律师 别人欠钱不还怎么办?2026最新完整维权指南 - 从来都是英雄出少年
  • 2026年Q2山东家用梯厂家专业度实测对比评测:山东三层电梯、山东二层电梯、山东别墅电梯、山东四层电梯、山东复式楼电梯选择指南 - 优质品牌商家
  • FDE:一个人 + AI,能不能跑通全栈?
  • 优雅的桌面歌词体验:LyricsX Swift插件深度解析
  • LoRA微调实战指南:企业级AI模型精准校准方法
  • 量子计算中qutrit电路优化与Steiner-Gauss算法应用
  • Ubuntu系统中telnet服务的配置与安全实践
  • 2026年净化公司TOP10榜单:无尘车间/GMP净化/无菌实验室/洁净室工程/手术室净化/食品车间/电子厂房/生物医药最新推荐 - 企业推荐官【官方】
  • Win10下Python虚拟环境激活报错:深入解析ExecutionPolicy权限与管理员模式解决方案
  • 基于PLC的立体仓库控制系统设计(设计源文件+万字报告+讲解)(支持资料、图片参考_降重降ai)_文章底部可以扫码
  • LangGraph多智能体协作效率:从理论模型到工程实践的量化分析
  • 消息队列顺序性保证实战
  • 集成学习在低资源语言情感分析中的应用:以波斯语社交媒体评论为例
  • RFDoc:面向证件检测的高效二进制局部特征描述符设计与实践
  • 无标签知识蒸馏:用动态合成数据训练轻量级人脸识别模型
  • 2026雨水收集系统厂家推荐榜:消防不锈钢水箱/焊接不锈钢水箱/生活不锈钢水箱/组合式不锈钢水箱/调蓄型雨水收集系统/选择指南 - 优质品牌商家
  • 11- Claude Code 最强插件库详解:从安装到全插件用途全吃透
  • SignFormer:基于Vision Transformer的静态手语识别模型解析与实战
  • KK-HF Patch:如何解决恋活!游戏体验的三大核心痛点?
  • 构建多图记忆系统VEKTOR:让AI智能体告别金鱼综合症
  • MHmarkets:平台工具、风控与体验体系观察
  • 保姆级教程:在Windows 10/11上配置Kaggle CLI并一键提交submission.csv
  • 明日方舟游戏资源库:技术开发者与创意工作者的完整解决方案
  • 美容平台支付失败率骤降91%:Lovable多通道聚合支付网关设计(含微信/支付宝/跨境PayPal容灾切换逻辑)
  • 利用Taotoken为内容创作平台集成多模型文本生成能力
  • 基于Transformer与知识图谱的药物重定位:2型糖尿病老药新用智能发现
  • 简单三步让Zotero中文文献管理效率提升10倍:Jasminum插件完全指南