Boolean icon button using Flutter

Argus Waikhom
2 min readOct 30, 2021

--

Whether you’re a web developer or mobile app developer, at some point in your developer life you may have to develop a boolean icon button.

So, what’s a boolean icon or a boolean icon button?

I bet you’ve seen it a million times on social media sites, e-commerce websites, even on Medium. Whether something is your favorite or not. Whether you’ve liked a post or you haven’t.

A boolean icon or a boolean icon button is a piece of UI with an icon whose UI state is going to change based on a boolean value.

Today, we’re gonna implement a very simple and easy boolean icon button using Flutter.

Let’s create a widget, BooleanCircleIconButton. It’s gonna have two icons and we’re gonna pick the icon to be displayed based on the value of the isActive variable.

The onTab function is a callback function, it’s gonna be triggered every time a user clicks the icon.

class BooleanCircleIconButton extends StatelessWidget {
final bool isActive;
final Icon activeIcon;
final Icon inactiveIicon;
final void Function() onTap;
const BooleanCircleIconButton({
Key? key,
required this.isActive,
required this.activeIcon,
required this.inactiveIicon,
required this.onTap,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Material(
shape: const CircleBorder(),
clipBehavior: Clip.hardEdge,
color: Colors.black12,
child: InkWell(
onTap: onTap,
child: Container(
padding: const EdgeInsets.all(12.0),
child: isActive ? activeIcon : inactiveIicon,
),
),
);
}
}

Call this widget from a parent widget.

bool isActive = false;...BooleanCircleIconButton(
isActive: isActive,
activeIcon: const Icon(Icons.star),
inactiveIicon: const Icon(Icons.star_border),
onTap: () {
isActive = !isActive;
setState(() {});
},
),

In the above example, since we update the value of the isActive value every time the onTap method executes, the icon will be updated every time you click it.

There you go, you got your boolean icon button.

If you want a little more customizable boolean icon button Flutter widget in your application, check out the source code on my GitHub.

If you find it useful give a clap or a star on the GitHub repo. :-)

Thank you for reading. I hope you like it. Have a great day. (●’◡’●)

--

--

Argus Waikhom
Argus Waikhom

No responses yet