Wigets学习之Icon

作者:renzp94
时间:2021-06-25 00:48:31

Icon

图标部件,用于显示图标

  • icon: 图标(必填),可以使用Icons指定值
  • size:图标大小
  • color:图标颜色
  • semanticLabel:语义化
  • textDirection:文本排列方式

注意:如果要使用默认的Material图标,需要在pubspec.yaml文件中设置如下:

flutter:
  uses-material-design: true
import 'package:flutter/material.dart';

void main() {
  runApp(App());
}

class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Row(
      textDirection: TextDirection.ltr,
      mainAxisAlignment: MainAxisAlignment.spaceAround,
      children: [
        Icon(
          Icons.ac_unit,
          textDirection: TextDirection.ltr,
          color: Colors.white,
          size: 30,
        ),
        Icon(
          Icons.access_alarm_outlined,
          textDirection: TextDirection.ltr,
          color: Colors.blue,
          size: 30,
        ),
        Icon(
          Icons.cake_outlined,
          textDirection: TextDirection.ltr,
          color: Colors.orange,
          size: 30,
        ),
      ],
    );
  }
}

使用自定义图标

要想使用自定义图标的话可以使用IconData来指定,下面使用iconfont来举例。

配置图标字体资源

iconfont官网将图标资源下载下来只复制iconfont.ttf文件到项目目录中如:lib/assets/fonts/iconfont.ttf
然后在pubspec.yaml文件中引入资源

name: learn
description: A new Flutter project.
version: 1.0.0+1
environment:
  sdk: '>=2.12.0 <3.0.0'

dependencies:
  flutter:
    sdk: flutter
  cupertino_icons: ^1.0.2

dev_dependencies:
  flutter_test:
    sdk: flutter

flutter:
  uses-material-design: true
+  fonts:
+    - family: iconFont
+      fonts:
+        - asset: lib/assets/fonts/iconfont.ttf

fonts配置项:

  • family:指定 fontFamily,可以用在需要指定fontFamily参数的位置
  • fonts:指定资源位置
  • weight:指定字体粗细,取值范围:100~900
  • style:指定斜体(italic)还是正常(normal)

注意:你可能在其他地方看到过,如果资源放在lib下则不需要再加上lib/,但是我实际测试如果不加则会报错找不到资源:Error: unable to locate asset entry in pubspec.yaml: "assets/fonts/iconfont.ttf".

使用图标

iconfont官网上找到图标的Unicode编码并将&#换成0使用,如:&#xe6080xe608,然后使用IconData

import 'package:flutter/material.dart';

void main() {
  runApp(App());
}

class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Row(
      textDirection: TextDirection.ltr,
      mainAxisAlignment: MainAxisAlignment.spaceAround,
      children: [
        Icon(
          IconData(0xe608, fontFamily: 'iconFont'),
          textDirection: TextDirection.ltr,
          color: Colors.white,
          size: 30,
        ),
        Icon(
          IconData(0xea0a, fontFamily: 'iconFont'),
          textDirection: TextDirection.ltr,
          color: Colors.white,
          size: 30,
        ),
        Icon(
          IconData(0xe640, fontFamily: 'iconFont'),
          textDirection: TextDirection.ltr,
          color: Colors.white,
          size: 30,
        ),
      ],
    );
  }
}