Flutter架构设计?
2025-06-05 本文已影响0人
Lucky_1122
1.通用组件(网络请求 日志 统计埋点。工具类)
2.通用业务组件(ui组件 分享组件 定位组件 三方登录组件,轮播组件 )
3.中间层(用来提供注册依赖和提供服务,实现服务)
4.业务组件A,B,C
业务组件组件不互相依赖,铜鼓中间组件进行通信
—结构图
lib/
├── common/ // 通用组件层
│ ├── network/ // 网络请求
│ ├── logger/ // 日志系统
│ └── utils/ // 工具类
│
├── business_components/ // 通用业务组件
│ ├── carousel/ // 轮播图
│ ├── share/ // 分享组件
│ └── button/ // 按钮组件
│
├── middle_layer/ // 中间层
│ ├── interfaces/ // 抽象接口
│ ├── services/ // 服务实现
│ └── bindings/ // 依赖注册
│
├── modules/ // 业务模块
│ ├── biz_a/ // 业务A
│ └── biz_b/ // 业务B
│
└── app.dart // 应用入口
实例代码如下:
// app.dart
void main() {
runApp(
GetMaterialApp(
title: '分层架构Demo',
initialRoute: AppRoutes.HOME,
getPages: AppPages.routes,
theme: ThemeData(primarySwatch: Colors.blue),
),
);
}
// home_page.dart
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('首页')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('欢迎使用分层架构Demo', style: TextStyle(fontSize: 20)),
SizedBox(height: 20),
ElevatedButton(
child: Text('进入业务A'),
onPressed: () => Get.find<NavigationService>().navigateToBizA(),
),
ElevatedButton(
child: Text('进入业务B'),
onPressed: () => Get.find<NavigationService>().navigateToBizB(),
),
],
),
),
);
}
}
路由表:// app_routes.dart
abstract class AppRoutes {
static const HOME = '/';
static const BIZ_A = '/bizA';
static const BIZ_B = '/bizB';
}
// app_pages.dart
class AppPages {
static final routes = [
GetPage(
name: AppRoutes.HOME,
page: () => HomePage(),
binding: AppBindings(), // 注册全局依赖
),
GetPage(
name: AppRoutes.BIZ_A,
page: () => BizAPage(),
binding: BizABinding(), // 注册业务A依赖
),
GetPage(
name: AppRoutes.BIZ_B,
page: () => BizBPage(),
binding: BizBBinding(), // 注册业务B依赖
),
];
}
一.通用组件
// common/network/network_client.dart
class NetworkClient {
Future<Map<String, dynamic>> get(String path) async {
await Future.delayed(Duration(milliseconds: 500));
return {'data': '来自 $path 的数据'};
}
}
// common/logger/logger.dart
class Logger {
void info(String message) => print('[INFO] $message');
void error(String message, [dynamic error]) => print('[ERROR] $message: $error');
}
二.通用业务组件
// business_components/carousel/carousel_component.dart
class CarouselComponent {
Widget buildCarousel({required List<String> images}) {
return Container(
height: 200,
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: images.length,
itemBuilder: (context, index) => Container(
margin: EdgeInsets.all(8),
child: Image.network(images[index], fit: BoxFit.cover),
),
),
);
}
}
// business_components/share/share_component.dart
class ShareComponent {
Future<void> share({required String title, String? url}) async {
print('分享内容: $title, URL: $url');
// 实际项目中调用平台分享API
}
}
三/中间层
1.定义服务
// middle_layer/interfaces/carousel_service.dart
abstract class CarouselService {
Widget buildCarousel({required List<String> images});
}
// middle_layer/interfaces/navigation_service.dart
abstract class NavigationService {
void navigateToBizA();
void navigateToBizB();
void goBack();
}
// middle_layer/interfaces/data_service.dart
abstract class DataService {
Future<String> fetchData(String path);
Future<void> shareContent(String title, String? url);
}
2.实现服务
// middle_layer/services/carousel_service_impl.dart
class CarouselServiceImpl implements CarouselService {
final CarouselComponent _carouselComponent = Get.find();
@override
Widget buildCarousel({required List<String> images}) {
// 中间层可添加额外业务逻辑
if (images.isEmpty) {
return Center(child: Text('暂无图片'));
}
return _carouselComponent.buildCarousel(images: images);
}
}
// middle_layer/services/navigation_service_impl.dart
class NavigationServiceImpl implements NavigationService {
@override
void navigateToBizA() => Get.toNamed('/bizA');
@override
void navigateToBizB() => Get.toNamed('/bizB');
@override
void goBack() => Get.back();
}
// middle_layer/services/data_service_impl.dart
class DataServiceImpl implements DataService {
final NetworkClient _network = Get.find();
final ShareComponent _share = Get.find();
final Logger _logger = Get.find();
@override
Future<String> fetchData(String path) async {
try {
_logger.info('开始请求数据: $path');
final result = await _network.get(path);
_logger.info('数据请求成功: $path');
return result['data'];
} catch (e) {
_logger.error('数据请求失败: $path', e);
rethrow;
}
}
@override
Future<void> shareContent(String title, String? url) async {
_logger.info('准备分享内容: $title');
await _share.share(title: title, url: url);
_logger.info('分享成功: $title');
}
}
3.依赖注册
// middle_layer/bindings/app_bindings.dart
class AppBindings extends Bindings {
@override
void dependencies() {
// 注册通用组件
Get.lazyPut<NetworkClient>(() => NetworkClient());
Get.lazyPut<Logger>(() => Logger());
Get.lazyPut<CarouselComponent>(() => CarouselComponent());
Get.lazyPut<ShareComponent>(() => ShareComponent());
// 注册中间层服务(依赖抽象接口)
Get.lazyPut<CarouselService>(() => CarouselServiceImpl());
Get.lazyPut<NavigationService>(() => NavigationServiceImpl());
Get.lazyPut<DataService>(() => DataServiceImpl());
}
}
四、业务组件
// modules/biz_a/biz_a_page.dart
class BizAPage extends GetView<BizAController> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('业务A')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
// 通过中间层服务获取组件
Get.find<CarouselService>().buildCarousel(
images: [
'https://picsum.photos/200/300?random=1',
'https://picsum.photos/200/300?random=2',
],
),
SizedBox(height: 20),
Obx(() => Text(controller.data.value)),
SizedBox(height: 20),
ElevatedButton(
child: Text('跳转到业务B'),
onPressed: () => Get.find<NavigationService>().navigateToBizB(),
),
ElevatedButton(
child: Text('分享业务A'),
onPressed: () => controller.shareContent(),
),
],
),
),
);
}
}
// modules/biz_a/biz_a_controller.dart
class BizAController extends GetxController {
final DataService _dataService = Get.find();
var data = '加载中...'.obs;
@override
void onInit() {
fetchData();
super.onInit();
}
Future<void> fetchData() async {
try {
final result = await _dataService.fetchData('/bizA/data');
data.value = result;
} catch (e) {
data.value = '数据加载失败';
}
}
void shareContent() {
_dataService.shareContent('业务A内容', 'https://example.com/bizA');
}
}
// modules/biz_a/biz_a_binding.dart
class BizABinding extends Bindings {
@override
void dependencies() {
Get.lazyPut<BizAController>(() => BizAController());
}
}