How do I add an onTap to individual images inside an index on Flutter?


Problem: I’m using a Toggle Button inside a grid with an index of images. When the user taps on different images the Toggle Button works and highlights the selected image with a blue border but it doesn’t trigger a specific action for that selected image with an OnPressed or OnTap.

My Solution: I’ve experimented with adding an onTap or OnPressed to an individual image inside the index but it says ‘This expression has a type of ‘void’ so its value can’t be used.’ and doesn’t work with a print statement.

class Backgrounds extends StatefulWidget {

  _BackgroundsState createState() => _BackgroundsState();

class _BackgroundsState extends State<Backgrounds> {

  List<bool> isSelected;

  void initState() {
    isSelected = [true, false, false, false, false, false, false, false, false];

  Widget build(BuildContext context) {
    var counter = 0;
    return GridView.count(
        padding: EdgeInsets.all(10),
        crossAxisCount: 3,
        mainAxisSpacing: 10,
        crossAxisSpacing: 8,
        children: [
         // Here is where I've added the onTap and the error comes up
            onTap: print('hi'),
            child: Image.asset('images/image1.png'
          ].asMap() {
          final index = ++counter - 1;
          return ToggleButtons(
    onPressed: (int index) {
    setState(() {
    for (int i = 0; i < isSelected.length; i++) {
    isSelected[i] = i == widget.key;
     isSelected: [isSelected[widget.key]],
    selectedBorderColor: Color(0xff2244C7),
            borderColor: Colors.transparent,
    borderWidth: 1,
    borderRadius: BorderRadius.all(Radius.circular(8),
    children: [widget.value],


It should be written like this :

onTap: () {do whatever you need;},

The error is complaining that the print you put there doesn’t return anything.

Answered By – amirala7

Answer Checked By – Mary Flores (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *