一、项目目录结构
bash
my_flutter_project/
├── android/ # Android平台代码
├── ios/ # iOS平台代码
├── lib/
│ ├── src/
│ │ ├── core/ # 核心层
│ │ │ ├── constants/ # 常量
│ │ │ │ ├── app_constants.dart # 应用常量
│ │ │ │ └── env_constants.dart # 环境常量
│ │ │ ├── routes/ # 路由配置
│ │ │ │ ├── app_pages.dart # 页面路由表
│ │ │ │ └── app_router.dart # 路由生成器
│ │ │ ├── theme/ # 主题配置
│ │ │ └── utils/ # 工具类
│ │ │ ├── dio_util.dart # 网络工具
│ │ │ └── storage_util.dart # 存储工具
│ │ ├── data/ # 数据层
│ │ │ ├── models/ # 数据模型
│ │ │ ├── repositories/ # 数据仓库
│ │ │ └── services/ # 数据服务(API接口)
│ │ ├── presentation/ # 表现层
│ │ │ ├── pages/ # 页面组件
│ │ │ ├── widgets/ # 公共组件
│ │ │ └── state/ # 状态管理
│ │ ├── config/ # 环境配置
│ │ │ └── app_config.dart
│ ├── assets/ # 静态资源
│ │ ├── images/ # 图片资源
│ │ ├── fonts/ # 字体文件
│ │ └── json/ # 本地JSON文件
│ ├── generated/ # 自动生成文件(如路由、本地化)
│ └── main.dart # 应用入口
├── test/ # 测试目录
├── scripts/ # 构建/部署脚本
├── environments/ # 环境配置文件
│ ├── dev.env
│ ├── staging.env
│ └── prod.env
└── pubspec.yaml # 依赖管理
二、环境配置
- 创建环境配置文件(environments/目录)
dart
// lib/src/config/app_config.dart
abstract class AppConfig {
String get apiBaseUrl;
String get envName;
bool get enableDebugLogs;
}
// 具体环境配置实现
class DevConfig implements AppConfig {
@override String get apiBaseUrl => 'https://api.dev.example.com';
@override String get envName => 'Development';
@override bool get enableDebugLogs => true;
}
class ProdConfig implements AppConfig {
@override String get apiBaseUrl => 'https://api.example.com';
@override String get envName => 'Production';
@override bool get enableDebugLogs => false;
}
- 在main.dart中初始化环境
dart
void main() async {
WidgetsFlutterBinding.ensureInitialized();
final appConfig = const String.fromEnvironment('ENV') == 'prod'
? ProdConfig()
: DevConfig();
runApp(MyApp(appConfig: appConfig));
}
- 启动时指定环境
bash
# 开发环境
flutter run --dart-define=ENV=dev
# 生产环境
flutter run --dart-define=ENV=prod
三、接口服务配置
- 使用Dio封装网络请求
dart
// lib/src/core/utils/dio_util.dart
class DioClient {
final Dio _dio = Dio();
DioClient(AppConfig config) {
_dio.options.baseUrl = config.apiBaseUrl;
_dio.interceptors.add(LogInterceptor(
requestBody: config.enableDebugLogs,
responseBody: config.enableDebugLogs,
));
_dio.interceptors.add(ErrorInterceptor());
}
// 封装GET请求
Future<Response> get(String path, {Map<String, dynamic>? params}) async {
return _dio.get(path, queryParameters: params);
}
// 统一错误处理
static handleError(DioError e) {
if (e.response?.statusCode == 401) {
// 跳转登录页面
}
// 其他统一错误处理逻辑
}
}
- 接口服务示例
dart
// lib/src/data/services/user_service.dart
class UserService {
final DioClient _client;
UserService(this._client);
Future<User> getUserProfile() async {
try {
final response = await _client.get('/user/profile');
return User.fromJson(response.data);
} on DioError catch (e) {
DioClient.handleError(e);
rethrow;
}
}
}
四、静态资源配置
- pubspec.yaml配置
yaml
flutter:
assets:
- assets/images/
- assets/json/
fonts:
- family: CustomIcons
fonts:
- asset: assets/fonts/custom_icons.ttf
- 图片资源管理
kotlin
assets/images/
├── home/
│ ├── home_icon.png
│ ├── [email protected]
│ └── [email protected]
└── profile/
└── avatar.png
- 资源引用类生成
dart
// lib/src/core/constants/app_constants.dart
class AppAssets {
static const String homeIcon = 'assets/images/home/home_icon.png';
static const String avatar = 'assets/images/profile/avatar.png';
}
// 使用示例
Image.asset(AppAssets.homeIcon)
五、性能优化策略
- 构建优化
dart
// 使用const构造函数
class MyWidget extends StatelessWidget {
const MyWidget({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return const Text('Optimized Widget');
}
}
- 列表性能优化
dart
ListView.builder(
itemCount: 1000,
itemBuilder: (context, index) {
return ListTile(
title: Text('Item $index'),
// 添加自动保持活跃
key: PageStorageKey('item_$index'),
);
},
// 添加项预加载
addAutomaticKeepAlives: true,
addRepaintBoundaries: true,
cacheExtent: 500,
);
- 图片优化
yaml
# pubspec.yaml
flutter:
uses-material-design: true
# 启用图片缓存优化
assets:
- assets/images/
- 重绘优化
dart
// 使用RepaintBoundary包裹频繁更新的组件
RepaintBoundary(
child: AnimatedContainer(
duration: const Duration(seconds: 1),
color: Colors.blue,
),
)
- 按需加载
dart
// 使用Visibility和延迟加载
Visibility(
visible: _showWidget,
child: const HeavyWidget(),
)
// 使用FutureBuilder延迟加载
FutureBuilder(
future: _loadData(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return DataWidget(snapshot.data!);
}
return const LoadingIndicator();
},
)
六、监控与调试
- 性能分析工具
bash
flutter run --profile # 性能分析模式
flutter build apk --analyze-size # 分析包大小
- 添加性能监控
dart
void main() {
WidgetsFlutterBinding.ensureInitialized();
if (kDebugMode) {
// 添加性能监控覆盖物
debugPaintSizeEnabled = false;
debugPrintRebuildDirtyWidgets = true;
}
runApp(const MyApp());
}
该架构具备以下优势:
- 清晰的层级划分(核心层/数据层/表现层)
- 完善的环境隔离机制
- 统一的网络请求处理
- 规范的资源管理
- 内置性能优化方案
- 良好的可扩展性