flutter / flutter

Flutter makes it easy and fast to build beautiful apps for mobile and beyond
https://flutter.dev
BSD 3-Clause "New" or "Revised" License
162.17k stars 26.65k forks source link

Icons: add method fromName(String iconName) #147434

Closed javaone199 closed 2 weeks ago

javaone199 commented 2 weeks ago

Use case

Could not reopen the issue #145302.

Icon names are retrieved from server. So a method for getting IconData from icon name is needed.

Icons.fromName(iconName)

iconName is the same as the constant name in Icons class.

pub.dev package material_icon_design_flutter does not contain many of the IconData constants defined in Icons, so it is not designed to provide name mappings for the Icons class.

Proposal

Add a new method for mapping names to IconData constants:

IconData Icons.fromName(iconName)

IconName are those already defined as constants such as more_vert.

IconData fromName(String iconName) {
   if (iconName=='more_vert') return Icons.more_vert;
   ....
}

or build a map from names to IconData constants.

osama383 commented 2 weeks ago

Hi. Interesting use case. Here is a possible solution.

Icon(Icons.more_vert);

If we look at the Icon constructor invoked above in the source code, we will see that the Icon class accepts an argument of type IconData and so Icons.more_vert is actually of type IconData.

In fact, Icons.more_vert is defined as follows:

static const IconData more_vert = IconData(0xe404, fontFamily: 'MaterialIcons');

If we next look at the constructor of the IconData class that is being invoked above, it reads as follows:

const IconData(
    this.codePoint, {
    this.fontFamily,
    this.fontPackage,
    this.matchTextDirection = false,
    this.fontFamilyFallback,
  });

Which means we really only need two pieces of information: the codePoint which is of type int and fontFamily which is of type string.

Instead of saving the string 'more_vert' in your database, you can save these two values and use them to build your icon.

int codePoint = Icons.more_vert.codePoint; String? fontFamily = Icons.more_vert.fontFamily;

Icon icon = Icon(IconData(codePoint, fontFamily: fontFamily));

javaone199 commented 2 weeks ago

From the IconData doc, instantiating IconData instead of using the predefined IconData constants will cause tree-shaking issue.

darshankawar commented 2 weeks ago

@javaone199 I'll reopen the original issue. Just make sure you respond to the question asked by the team member in that issue. https://github.com/flutter/flutter/issues/145302#issuecomment-2013138780 Closing this issue.

github-actions[bot] commented 1 day ago

This thread has been automatically locked since there has not been any recent activity after it was closed. If you are still experiencing a similar issue, please open a new bug, including the output of flutter doctor -v and a minimal reproduction of the issue.