Flutter虚拟机管理插件indie_vm的使用
Flutter虚拟机管理插件indie_vm的使用
Overview
IndieVM 是一种节省时间且极简的方式来处理 Flutter 应用中的 MVVM 架构。无论是初学者还是专业人士,这个微小的包都可以直接使用。
Installation
在项目中添加 indie_vm
插件:
dart pub add indie_vm
Usage
以下是一个完整的示例,展示如何使用 indie_vm
来管理页面的虚拟机(ViewModel)。
示例代码
import 'package:flutter/material.dart';
import 'package:state_beacon/state_beacon.dart'; // 引入状态管理工具
import 'package:get_it/get_it.dart'; // 引入依赖注入工具
// 定义 ViewModel 类,实现 IndieVM 接口
class ProfilePageVM implements IndieVM {
// 使用 GetIt 注入服务
final appServices = GetIt.instance<AccountService>();
// 使用 StateBeacon 管理可观察状态
final accountName = Beacon.writable("unknown");
[@override](/user/override)
void onDispose() {
// 页面销毁时清理资源
appServices.profilePageDismissed();
}
[@override](/user/override)
void onInit(BuildContext context) {
// 页面初始化时调用相关逻辑
appServices.profilePageEntered();
appServices.getAccountNameAsync(
onNameRetrieved: (String name) {
accountName.value = name; // 更新账户名称
},
);
}
}
// 定义页面类,继承自 IndieView
class ProfilePage extends IndieView<ProfilePageVM> {
ProfilePage({super.key});
[@override](/user/override)
Widget builder(BuildContext context, ProfilePageVM viewModel) {
// 使用 ViewModel 中的状态构建 UI
return Container(
child: Text(viewModel.accountName.watch(context)), // 监听状态变化并更新 UI
);
}
[@override](/user/override)
ProfilePageVM viewModelBuilder(BuildContext context) => ProfilePageVM(); // 返回 ViewModel 实例
}
更多关于Flutter虚拟机管理插件indie_vm的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
1 回复