FlutterAssetsGenerator,一款Flutter资源索引插件
引言
在Flutter中,资源的引用一般都需要现在根目录下定义一个目录,例如assets
,然后在pubspec.yaml
中配置目录,最后引用,写法一般如下:
Image.asset(
'assets/images/add.png',
width: 40,
height: 40,
),
这样引入资源总感觉很容易写错,目录和文件名都得写完整,手滑了一下就容易写错。因而又有了下面一种简化的方法:
///获取资源目录
String assetsPath(String name,
{String rootPath = 'assets/images/',
String dir = '',
String fileType = '.png'}) {
return '$rootPath$dir$name$fileType';
}
先定义一个类似于上面的方法,方法中对路径进行一下封装,因而使用资源文件的方式变成了下面这种:
Image.asset(
assetsPath('add'),
width: 40,
height: 40,
)
看起来是减少了不少要手写的地方,然而还是要手写一下文件名,文件后缀不同也需要再额外多写一点内容。而且还要再包一个方法,看起来也不是很好看。
FlutterAssetsGenerator
就是为了解决Flutter中资源引用这一个蛋疼的方式而来的。
介绍
如果有做过Android
开发的朋友应该都知道,在Android
中,资源的索引会有一个R
文件,这是一个自动生成的文件。放进资源drawable
目录里的资源,一般引用就用R.drawable.xx
方式引用,这样找资源首先很方便,再来也不会出现什么差错。
本插件想要实现的效果就是这样的,首先插件会遍历项目下的assets
目录,然后整理出文件索引,最后生成一个assets.dart
文件,如:
///This file is automatically generated. DO NOT EDIT, all your changes would be lost.
class Assets {
Assets._();
static const String imagesAdd = 'assets/images/add.png';
static const String imagesArrowDown = 'assets/images/arrow_down.png';
static const String imagesBack = 'assets/images/back.png';
static const String imagesBackWhite = 'assets/images/back_white.png';
static const String imagesBounds = 'assets/images/bounds.png';
static const String imagesCloseWhite = 'assets/images/close_white.png';
}
最后引用资源就可以如下了:
Image.asset(
Assets.imagesAdd,
width: 40,
height: 40,
)
这样有什么好处呢?首先资源整理到一起,方便查看,再来引用的时候都是直接引用常量,有代码提醒,也不怕写错了。插件实现的功能其实都是很简单的,也可以自己手写成这样,但是程序员能不手写肯定不会手写的啦。
使用
1、安装
插件已上传插件市场,因而打开Preferences
->Plugins
,在Marketplace
可以直接搜索安装。
2、配置assets目录
插件会从pubspec.yaml
文件下下读取assets目录,因此要使用本插件,你需要在pubspec.yaml
下配置资源目录:
flutter:
# The following line ensures that the Material Icons font is
# included with your application, so that you can use the icons in
# the material Icons class.
uses-material-design: true
# To add assets to your application, add an assets section, like this:
assets:
- assets/images/
3、使用
配置完成目录后,即可生成资源索引文件了:
插件默认的快捷键是Alt/Opt + G。
资源左侧的icon是可以点击的,点击可以定位到文件处。如果资源是svg,还会显示预览。(至于图片预览为啥还没显示,目前调试有点问题,所以还没展示)
4、设置
插件默认生成的文件目录在lib/generated目录下,如果你不喜欢,你可以自己更改,目录支持多级,以/
分割。索引文件的类名默认是Assets
,如果你希望Android
一点,你也可以改为R
。
插件默认打开了自动检测功能,如果不需要的时候可以关掉。
资源索引默认命名是小驼峰式,更符合dart
语言规范。开启Named with parent
会为资源索引加上一级文件夹名,如果有重名的会再多取一级,如果想要索引短一点,可以关掉此选项。
最后附上github地址,欢迎star,使用插件有什么问题或者建议,欢迎提出!