How to paint half an Icon in flutter

587

as an option

class HalfFilledIcon extends StatelessWidget {
  final IconData icon;
  final double size;
  final Color color;

  HalfFilledIcon({this.icon, this.size, this.color});

  @override
  Widget build(BuildContext context) {
    return ShaderMask(
      blendMode: BlendMode.srcATop,
      shaderCallback: (Rect rect) {
        return LinearGradient(
          stops: [0, 0.5, 0.5],
          colors: [color, color, color.withOpacity(0)],
        ).createShader(rect);
      },
      child: SizedBox(
        width: size,
        height: size,
        child: Icon(icon, size: size, color: Colors.grey[300]),
      ),
    );
  }
}

how to use:

import 'package:flutter/material.dart';

void main() => runApp(MaterialApp(debugShowCheckedModeBanner: false, home: Home()));

class Home extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: HalfFilledIcon(icon: Icons.circle, size: 80, color: Colors.green),
      ),
    );
  }
}

enter image description here

Share:
587
bihire boris
Author by

bihire boris

I am a full stack developer. During my carrieer so far, I've developed software for mostly two platforms: mobile and web browsers. I can't live without Git. I like working on projects that make life easier.

Updated on December 26, 2022

Comments

  • bihire boris
    bihire boris over 1 year

    I needed the rounded circle icon with two parts ,with different colors.

    I tried using a ShadeMask my try seems very off.

    Note: I don't need a a gradient just one part a color and the other another color

    can someone give a hand. enter image description here

    class HalfFilledIcon extends StatelessWidget {
      HalfFilledIcon(
        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,
            height: size,
            child: Icon(
              icon,
              size: size,
              color: Colors.grey[300],
            ),
          ),
          shaderCallback: (Rect bounds) {
            final Rect rect = Rect.fromLTRB(0, 0, size / 2, 0);
            return gradient.createShader(rect);
          },
        );
      }
    }