Home > Back-end >  How to add PNG asset as IconData?
How to add PNG asset as IconData?

Time:07-28

I have png asset and I want to put it as Icon, but solutions that I found are not working.

Here is what I have now:

GradientIcon(
          ImageIcon(
            AssetImage('assets/svg/icons/discoball'),
          ),
          size.width * 0.15,
          const LinearGradient(
            stops: [
              0.25,
              0.75,
            ],
            colors: [Color(0xffff7a00), Color(0xffff00d6)],
          ),
        ),

and this is GradientIcon class

class GradientIcon extends StatelessWidget {
  const GradientIcon(
    this.icon,
    this.size,
    this.gradient,
  );

  final IconData icon;
  final double? size;
  final Gradient gradient;

  @override
  Widget build(BuildContext context) {
    return ShaderMask(
      child: SizedBox(
        width: size! * 2,
        height: size! * 1.2,
        child: Icon(
          icon,
          size: size,
          color: Colors.white,
        ),
      ),
      shaderCallback: (Rect bounds) {
        return gradient.createShader(bounds);
      },
    );
  }
}

and I am getting this error

The argument type 'ImageIcon' can't be assigned to the parameter type 'IconData'.

Why this is not working? How to do it?

CodePudding user response:

You can modify the GradientIcon that will accept widget.

class GradientIcon extends StatelessWidget {
  const GradientIcon(
    this.child,
    this.size,
    this.gradient,
    {super.key}
  );

  final Widget child;
  final double? size;
  final Gradient gradient;

  @override
  Widget build(BuildContext context) {
    return ShaderMask(
      child: SizedBox(
        width: size! * 2,
        height: size! * 1.2,
        child: child,
      ),
      shaderCallback: (Rect bounds) {
        return gradient.createShader(bounds);
      },
    );
  }
}

Also, I would prefer named constructor

const GradientIcon({
  Key? key,
  required this.child,
  this.size,
  required this.gradient,
}) : super(key: key);

CodePudding user response:

  1. Go to FlutterIcon.com

  2. Drag and drop all your Icons

  3. Give a class name (Let's say CustomIcons)

  4. Download and Unzip.

  5. Copy fonts folder to your app folder and add the fonts as you add a normal font in flutter. (See here how to add a custom font).

  6. Copy custom class CustomIcons that we generated to your lib directory.

  7. Use CustomIcons as IconData :

     Icon(CustomIcons.hamburger)
    
  • Related