无需Getx包,Flutter实现MVC架构及状态管理的可行方案咨询
Flutter MVC架构下的轻量状态管理方案(不依赖GetX)
如果你只需要状态管理功能,不想引入GetX的冗余特性,完全有更轻量化、更贴合MVC的实现方案,分为原生/官方生态方案和轻量第三方包两类:
一、原生+官方轻量包实现(无冗余功能)
1. ChangeNotifier + Provider(官方推荐,仅做状态同步)
Provider是Flutter官方生态里的轻量状态管理工具,完全聚焦状态同步,没有额外附带功能。在MVC架构中分工明确:
- Model:继承
ChangeNotifier,封装状态和核心业务逻辑,状态变更时调用notifyListeners()触发UI更新 - Controller:作为View和Model的中间层,负责调用Model的方法、处理业务逻辑(简单场景下可直接让View与Model交互,省略Controller)
- View:通过
Consumer或Provider.of监听Model状态,自动刷新UI
示例代码:
// Model class CounterModel extends ChangeNotifier { int _count = 0; int get count => _count; void increment() { _count++; notifyListeners(); // 通知UI更新 } } // Controller(可选,简化场景可省略) class CounterController { final CounterModel model; CounterController(this.model); void onIncrementPressed() { model.increment(); } } // View class CounterView extends StatelessWidget { @override Widget build(BuildContext context) { final controller = CounterController(Provider.of<CounterModel>(context)); return Scaffold( body: Center( child: Consumer<CounterModel>( builder: (context, model, child) => Text('Count: ${model.count}'), ), ), floatingActionButton: FloatingActionButton( onPressed: controller.onIncrementPressed, child: Icon(Icons.add), ), ); } } // 全局注入Model void main() { runApp( ChangeNotifierProvider( create: (context) => CounterModel(), child: MyApp(), ), ); }
2. 纯原生StatefulWidget + 回调(无第三方包依赖)
如果完全不想用任何第三方包,用原生StatefulWidget结合回调就能实现简单MVC状态管理:
- Model:普通类保存状态,提供状态变更的回调接口
- Controller:持有Model,处理业务逻辑,状态变化时触发回调通知View
- View:StatefulWidget,注册回调后通过
setState()刷新UI
示例代码:
// Model class CounterModel { int count = 0; void Function()? onCountChanged; void increment() { count++; onCountChanged?.call(); } } // Controller class CounterController { final CounterModel model = CounterModel(); void incrementCounter() { model.increment(); } } // View class CounterView extends StatefulWidget { @override _CounterViewState createState() => _CounterViewState(); } class _CounterViewState extends State<CounterView> { final CounterController controller = CounterController(); @override void initState() { super.initState(); controller.model.onCountChanged = () { setState(() {}); // 触发UI更新 }; } @override Widget build(BuildContext context) { return Scaffold( body: Center(child: Text('Count: ${controller.model.count}')), floatingActionButton: FloatingActionButton( onPressed: controller.incrementCounter, child: Icon(Icons.add), ), ); } }
二、轻量第三方状态管理包(仅专注状态管理)
1. Riverpod(Provider升级版,更灵活)
Riverpod是Provider的继任者,完全脱离BuildContext限制,功能纯粹聚焦状态管理,没有GetX的路由、依赖注入等冗余特性。在MVC架构中,Model封装状态逻辑,View通过Consumer监听状态,Controller负责业务调度。
2. Cubit(Bloc的简化版,聚焦状态流转)
如果你的应用有复杂的状态流转需求,Cubit是Bloc库的轻量化版本,仅处理事件和输出状态,比完整Bloc更简洁,同样只专注状态管理。
3. MobX(响应式状态管理)
MobX通过响应式编程实现状态同步,只需标记可观察状态和动作,无需手动调用通知方法,风格简洁,完全聚焦状态管理,没有额外冗余功能。
内容的提问来源于stack exchange,提问作者Gwhyyy
相关产品推荐
相关产品推荐

