Adding Border to Icons flutter
Asked Answered
C

2

6

I want to add border to the icons in flutter like in the image below.

Star with border color

How can I achieve that?

Chengtu answered 28/8, 2020 at 7:23 Comment(1)
So....I assume we must have an alternative then..right?Chengtu
M
9

I tried something creative

Stack(
  children: [
     _buildIcon(48, Colors.blue),
     _buildIcon(44, Colors.white),
  ],
),

Widget _buildIcon(double size, Color color) {
  return Container(
    height: 48,
    width: 48,
    alignment: Alignment.center,
    child: Icon(
      Icons.star,
      color: color,
      size: size,
    ),
  );
}
Misusage answered 28/8, 2020 at 7:35 Comment(0)
L
2

The accepted answer works well for simple, filled icons like the star in the example. If you have a more complex icon (e.g. with thin lines), you will quickly run into alignment issues.

I solved this by using stacked shadows:

import 'package:flutter/material.dart';

/// A widget that outlines an icon
class OutlinedIcon extends StatelessWidget {
  const OutlinedIcon(
    this.iconData, {
    super.key,
    this.color,
    this.size,
  });

  /// The iconData to be displayed
  final IconData iconData;

  /// The color of the icon
  final Color? color;

  /// The size of the icon
  final double? size;

  @override
  Widget build(BuildContext context) {
    return Icon(
      iconData,
      size: size,
      color: color,
      shadows: List.generate(
        10,
        (index) => Shadow(
          blurRadius: 2,
          color: Theme.of(context).canvasColor,
        ),
      ),
    );
  }
}

This gives me the following effect:

enter image description here ------> enter image description here

You can change the intensity of the shadow by varying blur and the number of shadows in the stack. Definitely not perfect (you're rendering 10 shadows instead of one outlined widget, and the border is slightly blurry) but good enough for my purposes...

Levator answered 19/1 at 15:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.