Skip to main content

04 flutter项目中使用iconfont图标

1 准备好iconfont图标

iconfontUnicode把图标下载下来,并 解压后目录如下:

.
├── demo.css
├── demo_index.html
├── iconfont.css
├── iconfont.js
├── iconfont.json
├── iconfont.ttf
├── iconfont.woff
└── iconfont.woff2

0 directories, 8 files

flutter项目只需用到iconfont.cssiconfont.ttf这2个文件.把这2个文放到, flutter项目根目录下的asstes/fonts/目录下,没有则自行创建.

2 安装css转换dart的库

iconfont.css原本用于web端的样式,并不能用于dart,需要把css的相关内容转换为 dart,相关的样式才能在flutter内生效.

在pubspec.yaml加入以下配置
# ...
dependencies:
iconfont_css_to_class:
git:
url: https://gitee.com/yin_shiyong/iconfont_css_to_class.git
ref: 0.1.3
# ...

flutter:
fonts:
- family: IconFont
fonts:
- asset: assets/fonts/iconfont.ttf
# ...

并执行flutter pub get,安装依赖

3 把iconfont.css转换为dart文件,

flutter的项目中,他创建lib/common/目录,然后在项目的根目录下执行,

$ flutter pub run iconfont_css_to_class:main
Successfully: 已根据 assets/fonts/iconfont.css 创建出 lib/common/iconfont.dart

4 在项目中使用

import '../../../../../common/iconfont.dart';

class ItemSection extends StatelessWidget {
const ItemSection({Key? key}) : super(key: key);


Widget build(BuildContext context) {
return Container(
child: const Icon(
IconFont.icon_file_directory,
),
);
}
}