一段简单的 python 脚本,用来生成资源图片对应的dart文件,方便业务代码中调用
一、使用
python 脚本放在项目的根目录
在 pubspec.yaml 正常配置资源路径
assets:
- images/
运行 python3 res.py ,自动在 lib/res 中生成 res_images.dart 的文件
代码中调用静态的常量
Image.asset(ResImage.ic_chat,width: 48,height: 48)
二、python 的脚本
脚本比较简单,直接贴在这里了。做了一些备注,方便大家修改。
import os
import time
# 获取当前脚本所在文件夹路径
curPath = os.getcwd()
# 图片所在目录
imageCatalog="images";
# 图片路径
imagesPath=curPath+"/"+imageCatalog
# 读取图片
images=os.listdir(imagesPath)
# 生成的资源文件路径
filePathParent=curPath+"/lib/res"
filePath=curPath+"/lib/res/res_images.dart"
if not os.path.exists(filePathParent):
os.makedirs(filePathParent)
# 资源文件读写
resFile=open(filePath,'w+')
resFileStrContent=""
for s in images:
if(s.endswith('.png')):
s_split = s.split('.')
resFileStrContent += "\n static const "+s_split[0]+" = "+"\""+imageCatalog+"/"+s+"\";"
t=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
# 最后要写入的字符串
resFileStr="///脚本自动生成对应的图片资源文件\n///"+t+"\n\nclass ResImage {"+resFileStrContent+"\n}"
print(resFileStr)
resFile.write(resFileStr)
resFile.close()