iconfont.com 有 500w 个图标,而且各个公司的设计师还在源源不断的为其增加新的图标,此库仅为了更便捷的在 Flutter 中使用 Iconfont 字体图标库
准备工作
从 iconfont.com 网站选择上下载字体包,解压并拷贝 demo_index.html
和 iconfont.ttf
到项目中
- your-project
- ios
- android
- lib
- fonts
# 根据此 html 文件进行解析,所以编译前需要保留
demo_index.html
iconfont.ttf
复制代码
编辑 pubspec.yaml, 引用文字资源
fonts:
- family: Iconfont
fonts:
- asset: fonts/iconfont.ttf
复制代码
安装 iconfont_builder 至 dart 全局
请确保电脑有 dart 环境,如果没有请执行安装 dart:
$ brew install dart
复制代码
将 iconfont_builder 安装至 dart 全局,作为命令行工具进行使用:
$ pub global activate iconfont_builder
复制代码
在 Flutter 中使用 Iconfont
使用 iconfont_builder 编译 Iconfont.dart 文件
$ iconfont_builder --from ./fonts --to ./lib/Iconfont.dart
复制代码
可以浏览一下刚刚生成的 lib/Iconfont.dart
, 里面其实就是图标名的映射:
class Iconfont {
// iconName: all
static const all = IconData(
0xe697,
fontFamily: 'Iconfont',
matchTextDirection: true,
);
// iconName: back
static const back = IconData(
0xe698,
fontFamily: 'Iconfont',
matchTextDirection: true,
);
...
复制代码
将图标名作为属性有一个好处就是使用起来 dart 会有很好的提示
有的图标命名很随意,甚至有中文名称,iconfont_builder 已经将不符合 dart 命名规范的名称都做了格式化,并且保留了原有的名称作为注释。
import './Iconfont.dart';
void main() {
// iconfont 中的图标名字都会映射置 Iconfont 对象中
// Iconfont.local 是一个 IconData 对象
final theIcon = Icon(Iconfont.local);
// ...
}
复制代码
自定义Iconfont类名
默认的类名为 Iconfont,编译时,添加 --class 类名
命令,可替换 Iconfont
类名
$ iconfont_builder --from ./fonts --to ./lib/Iconfont.dart --class Icn
复制代码
然后用新的类名进行引用:
import './Iconfont.dart';
void main() {
final theIcon = Icon(Icn.name);
}
复制代码
自定义字体名
iconfont_builder 默认使用 Iconfont
作为 font-family
, 而有时候我们可能同时使用多个字体, 此时我们需要自定义字体名。
编译时,添加 --family 字体名
命令,替换 Iconfont
字体名:
$ iconfont_builder --from ./fonts --to ./lib/Iconfont.dart --family OtherIcon
复制代码
然后编辑 pubspec.yaml, 引用刚刚设定的字体名
fonts:
- family: OtherIcon
fonts:
- asset: fonts/iconfont.ttf
复制代码
使用 Icon 组件模式
默认编译的是 IconData 对象,这和 Flutter 默认的 Icons 使用习惯一致,如果需要更简短的使用,可以直接编译成Icon 组件。
使用 iconfont 编译 Iconfont.dart, 添加 --type Icon
命令:
$ iconfont_builder --type Icon --from ./fonts --to ./lib/Iconfont.dart
复制代码
import './Iconfont.dart';
void main() {
// 此时,Iconfont.name 是一个函数,直接返回一个 Icon 组件
final theIcon = Iconfont.data();
}
复制代码
查看帮助
$ iconfont_builder --help
复制代码