使用Flutter官方Icons图标

Material Design所有图标可以在其官网查看:https://material.io/tools/icons/

import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(
    home: Scaffold(
      appBar: AppBar(
        title: const Text('你好Flutter'),
        backgroundColor: Colors.blueGrey[900],
      ),
      body: const MyApp(),
    ),
  ));
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return Center(
        child: Column(
      children: const [
        Icon(Icons.search, color: Colors.red, size: 40),
        SizedBox(height: 10),
        Icon(Icons.home),
        SizedBox(height: 10),
        Icon(Icons.category),
        SizedBox(height: 10),
        Icon(Icons.shop),
        SizedBox(height: 10),
      ],
    ));
  }
}

Flutter中借助阿里巴巴图标库自定义字体图标

我们也可以使用自定义字体图标。阿里巴巴图标库官网 iconfont.cn上有很多字体图标素材,我们可以选择自己需要的图标打包下载后,会生成一些不同格式的字体文件,在Flutter中,我们使用ttf格式即可。

假设我们项目中需要使用一个书籍图标和微信图标,我们打包下载后导入:

  1. 导入字体图标文件;这一步和导入字体文件相同,假设我们的字体图标文件保存在项目根目录下,路径为"fonts/iconfont.ttf":
  2. 在pubspec.yaml加入
    • font

也可以配置多个字体文件:

fonts:
    - family: myIcon #指定一个字体名
fonts:
    - asset: fonts/iconfont.ttf
    - family: alipayIcon #指定一个字体名
fonts:
    - asset: fonts/iconfont2.ttf
  1. 为了使用方便,我们定义一个MyIcons 类,功能和Icons 类一样:将字体文件中的所有图标都定义成静态变量:
// myicon 文件
import 'package:flutter/material.dart';

class MyIcon {
  static const IconData gaiqian = IconData(
    0xe6b7,
    fontFamily: 'myicon',
    matchTextDirection: true
  );
  static const IconData chaxun1 = IconData(
    0xe74f,
    fontFamily: 'myicon',
    matchTextDirection: true
  );
  static const IconData zhuanhuan = IconData(
    0xe621,
    fontFamily: 'myicon',
    matchTextDirection: true
  );
}
// main调用
import 'package:flutter/material.dart';
import 'myicon.dart';

void main() {
  runApp(MaterialApp(
    home: Scaffold(
      appBar: AppBar(
        title: const Text('你好Flutter'),
        backgroundColor: Colors.blueGrey[900],
      ),
      body: const MyApp(),
    ),
  ));
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return Center(
        child: Column(
      children: const [
        Icon(MyIcon.gaiqian, color: Colors.red, size: 40),
        SizedBox(height: 10),
        Icon(MyIcon.chaxun1),
        SizedBox(height: 10),
        Icon(MyIcon.zhuanhuan, color: Colors.green, size: 40),
        SizedBox(height: 10),
      ],
    ));
  }
}

results matching ""

    No results matching ""