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应用。
Flutter MVC架构详解:经典架构模式实战
发布时间:2026/5/27 1:04:04
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应用。