Use custom Icon in Flutter

  dart, flutter, Front end, icon, ui

图片描述

1. Preface

FlutterAs one of the most popular technologies at present, it has already attracted the attention of a large number of technology lovers, even some, due to its excellent performance and smooth multi-terminal differences.Idle fish,meituan,TencentSuch large companies have been put into production. Although its ecology is not fully mature at present, it depends on what is behind it.GoogleBlessing, its development speed has been amazing enough to predict the futureFlutterThe demand for developers will also grow.

It has been 9102 years for the sake of the current technology taste and the future trend. As a front-end developer, there seems to be no reason not to try it. It is with this mentality that the author also began to learnFlutterAt the same time, we have built a trainingWarehouse, all subsequent code will be hosted on it, welcome star, learn together. This is my Flutter series:

The content to be shared today is actually very simple, as we all know.FlutterOne set is built inMaterial DesignStylishIcon iconHowever, for a mature App, it is usually far from enough. To this end, we need to introduce customIcon icon.

This article will focus onAnt DesignTake the library as an example to introduce how toFlutterIntroduction of custom icon in.

2. Preparation: Font File

As the saying goes, “It is impossible for a skillful woman to cook without rice”. To introduce custom icons, we must first prepare icon font files (.ttfSuffix). For large companies, it is enough to find a visual classmate. But if it’s an amateur project we do or when we don’t have the resources, we can do it.Alibaba vector libraryPick your favorite icon.

Here is toAnt Design official logo libraryFor example (a total of 600 icons), we add icon font files to the project by:

Add shopping cart-> click shopping cart-> download code-> extract-> copy to project (renamable)

步骤1

步骤2

步骤3

3. Declare custom fonts

It is not enough to just copy the font file into the project, we need to passstatementThe way to tellFlutterNew fonts are available. Open thepubspec.yamlFile, foundfontsThis paragraph:

To add custom fonts to your application, add a fonts section here, in this “flutter” section. Each entry in this list should have a “family” key with the font family name, and a “fonts” key with a list giving the asset and other descriptors for the font.

Comments are statements that let us add custom fonts to the bottom of this paragraph of text. Combined with examples of comments and the current project directory, we can configure them as follows:

项目工程目录结构
.
├── README.md
├── android
│   └── app
├── assets
│   └── fonts
│       └── AntdIcons.ttf
├── flutter_training_app.iml
├── ios
│   └── Flutter
├── lib
│   └── main.dart
├── pubspec.lock
└── pubspec.yaml

字体声明
fonts:
  - family: AntdIcons
    fonts:
      - asset: assets/fonts/AntdIcons.ttf

Note:After the configuration, be sure to execute itflutter packages getCommand and recompile the project, otherwise the font file cannot be used.

4. write custom IconData

In fact, so far, we have been able to use the icon just downloaded, just like the following code:

Icon(
  IconData(0xe77d, fontFamily: 'AntdIcons'),
  size: 20,
  color: Colors.black
)

among themfontFamilyThe value of'AntdIcons'Is the new font we just announced, but in the code0xe77dWhere does the value come from? Open the folder downloaded and decompressed before again, one of which isdemo_index.htmlFile, open it in the browser, we can see the following picture:

Unicode图标类型对照表

InUnicodeUnder this Tab, we can see that it gives all the icons in a thoughtful way.TypeAndUnicode codeContrast relation. So theoretically, we only need to copy which icon we want to use.UnicodeJust code it into the code.

However, this is obviously not very friendly. First of all, every time we use itIconBefore this, we have to look up from this relational table. Secondly, are you sure what icon this string of numbers corresponds to next time you see it in your code (not to mention others)? Therefore, we need a more elegant way to manage custom icons.

In fact, it is also simple, we can create a custom icon class:

class AntdIcons {
  static const IconData checkCircle = IconData(0xe77d, fontFamily: 'AntdIcons');
  static const IconData CI = IconData(0xe77e, fontFamily: 'AntdIcons');
  static const IconData Dollar = IconData(0xe77f, fontFamily: 'AntdIcons');
  ...
}

Then the usage becomes:

Icon(
  AntdIcons.checkCircle,
  size: 20,
  color: Colors.black
)

The above code is completely equivalent to the previous direct useUnicode codeThe effect of. However, if we want to use all the icons, we still need to enrich them.AntdIconsThis class. To this end, you can write a small script, indemo_index.htmlIt can be defined by running in the console of the browser window.IconDataThe code for:

function camelCase(str) {
  return str.replace(/[ -]+(\w)/g, (match, char) => char.toUpperCase());
}

function makeCode({name, code}) {
  return `static const IconData ${camelCase(name)} = IconData(0${code.substr(2, 5)}, fontFamily: 'antd-icons');\n`;
}

Array
  .from(document.querySelectorAll('.unicode .dib'))
  .map(element => {
    return {
      name: element.querySelector('.name').innerText,
      code: element.querySelector('.code-name').innerText
    };
  })
  .map(makeCode)
  .join('\n');

PS: Individual minor errors may be caused in the output result due to the nonstandard naming of the icon author. Manual modification is sufficient, and the complete file can be viewed.Here.

Next, it’s time to have fun ~ ~ ~

Ant Design图标示例

5. Summary

Through a practical exampleAnt DesignIcon example, details how to inFlutterIntroduction of custom icons in, hoping to help you oh ~

All code in this article is managed inHere, can also pay attention to myBlogWelcome to study together ~