I want to add border to the icons in flutter like in the image below.
How can I achieve that?
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,
),
);
}
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:
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...
© 2022 - 2024 — McMap. All rights reserved.