flutter-图片资源路径管理
目录
flutter 图片资源路径管理
1 创建统一资源管理类
- 创建一个单独的 Dart 文件(比如 manager.dart),将所有图片路径集中管理。这样在引用图片时,不需要每次都手动输入完整路径,只需通过常量引用即可。 //manager.dart class Manager { static const String _imagePath = ‘assets/images/’; static const String logo = ‘${_imagePath}logo.png’; static const String background =’${_imagePath}background.png’; } //引用: csharp Image.asset(Manager.logo);
2 使用 flutter_gen 自动生成代码
可以使用 flutter_gen 这个插件,它会根据 pubspec.yaml 中声明的资源文件自动生成代码。
- 添加依赖 在 pubspec.yaml 中添加: dev_dependencies: build_runner: any flutter_gen_runner: any
- 配置资源路径 在 pubspec.yaml 中正确配置资源路径: flutter: assets:
- assets/images/
- 运行生成命令 运行以下命令生成资源管理代码: flutter packages pub run build_runner build 生成的代码通常会在 lib/gen/assets.gen.dart 文件中,可以直接通过常量引用图片: import ‘package:your_project/gen/assets.gen.dart’; Image.asset(Assets.images.logo.path); flutter_gen 不仅支持图片,还可以管理字体、SVG 文件等其他资源。 4 自定义导出文件名称 在pubspec.yaml新增以下内容,output就是要导出的文件名 flutter_gen: output: lib/picture/