【笔记】Flutter的Icon图标组件

前言

Flutter的Icon图标组件学习笔记

Icon图标组件

加载图标

加载内置图标

  • 通过Icons,获取内置图标
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import 'package:flutter/material.dart';

void main() {
runApp(MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text("文本内容"),
),
body: const Column(
children: [
App(),
],
),
),
));
}

class App extends StatelessWidget {
const App({super.key});

@override
Widget build(BuildContext context) {
return const Column(
children: [
Icon(Icons.home)
],
);
}
}

加载第三方图标

加载阿里巴巴图标iconfont
  • 以抖音图标为例
下载图标


  • 在项目的根目录创建一个fonts目录
  • 将下载后的压缩包解压,将其中的iconfont.jsoniconfont.ttf移动到项目的fonts目录下

iconfont.json文件仅用来查找family字段值和图标所对应的unicode字段值,用完后可以删掉无需一直保留

1
2
3
4
+ 项目名
+ fonts
- iconfont.json
- iconfont.ttf
修改配置文件
  • 加载字体静态资源

family:在fonts/iconfont.json中找到family字段的值

pubspec.yaml
1
2
3
4
5
flutter:
fonts:
- family: iconfont
fonts:
- asset: fonts/iconfont.ttf
创建一个自定义字体类
  • 在lib目录下创建一个IconFont.dart

0xe8db:在fonts/iconfont.json中找到对应图标的unicode字段的值,添加0x作为前缀
fontFamily:在pubspec.yaml中找到对应图标的family字段的值

lib/IconFont.dart
1
2
3
4
5
6
7
8
9
10
11
import 'package:flutter/material.dart';

class IconFont {

static const IconData douyin = IconData(
0xe8db,
fontFamily: "iconfont",
matchTextDirection: true
);

}
加载第三方图标
  • 引入自定义字体类,通过自定义字体类中的静态属性加载第三方图标
lib/main.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import 'package:flutter/material.dart';
import 'IconFont.dart';

void main() {
runApp(MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text("文本内容"),
),
body: const Column(
children: [
App(),
],
),
),
));
}

class App extends StatelessWidget {
const App({super.key});

@override
Widget build(BuildContext context) {
return const Column(
children: [
Icon(IconFont.douyin)
],
);
}
}

指定图标颜色

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import 'package:flutter/material.dart';

void main() {
runApp(MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text("文本内容"),
),
body: const Column(
children: [
App(),
],
),
),
));
}

class App extends StatelessWidget {
const App({super.key});

@override
Widget build(BuildContext context) {
return const Column(
children: [
Icon(
Icons.home,
color: Colors.red,
)
],
);
}
}

指定图标大小

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import 'package:flutter/material.dart';

void main() {
runApp(MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text("文本内容"),
),
body: const Column(
children: [
App(),
],
),
),
));
}

class App extends StatelessWidget {
const App({super.key});

@override
Widget build(BuildContext context) {
return const Column(
children: [
Icon(
Icons.home,
size: 10,
)
],
);
}
}

完成

参考文献

哔哩哔哩——筱筱知晓