Search code examples
fluttersvgiconsextension-methods

How can I add it to Icon with svg extension?


I want to create my own icons. For this, I created CustomIcon with the extension.

extension CustomIcons on Icon {
  Icon get panelIcon =>Icon(
      icon: SvgPicture.asset("asset/svg/one.svg", semanticsLabel: 'One') ,
      color: Colors.red,
    );
     
}

}

I want to use my CustomIcon in the form of Icon(Icons.panelIcon). I am getting the error in the photo. How can I do this?

enter image description here


Solution

  • Few things to know :

    • The parameter icon of Icon class is of type IconData?.
    • IconData is font character and not an image. It is part of "MaterialIcons" font.

    enter image description here

    Here are the steps to achieve it :

    1. Make an extension on Icons class and not Icon.

    2. Create a custom font with your svg pictures using this website : https://icomoon.io/app

    3. Import the font in your flutter project assets

    4. Write your code like so

    extension customIcons on Icons {
      static IconData panelIcon = const IconData(0x[CHARACTER_CODE], fontFamily: 'YourCustomIconFont');
    }
    

    NB: You will easily get CHARACTER_CODE on iconmoon.io. Check this as example. 👇🏽