-1

In Flutter, when I tap on an icon, I want to print out the icon name. Here is my code:

_showIconGrid() {
    var ls = [
      Icons.extension,
      Icons.face,
      Icons.fastfood,
      Icons.favorite,
      Icons.favorite_border,
      Icons.home,
    ];

    return GridView.count(
      crossAxisCount: 8,
      children: List.generate(ls.length, (index) {
        var iconData = ls[index];
        return IconButton(
            onPressed: () {
              //here I would like to get the icon name e.g "Icons.flight"
              
            },
            icon: Icon(
              iconData,
            ));
      }),
    );
  }

When the user clicks on an Icon, I should be able to see which icon the user has tapped.

randomUser786
  • 1,527
  • 3
  • 13
  • 25

3 Answers3

1

You can copy paste run full code below
You can use GlobalKey and https://pub.dev/packages/icons_helper
Wither GlobalKey to get current icon and use icon_helper to compare code point and print

code snippet

var keyList = [
      GlobalKey(),
      GlobalKey(),
      GlobalKey(),
      GlobalKey(),
      GlobalKey(),
      GlobalKey()
    ];
return GridView.count(
  crossAxisCount: 8,
  children: List.generate(ls.length, (index) {
    var iconData = ls[index];
    return IconButton(
        key: keyList[index],
        onPressed: () {
          IconButton iconbutton = keyList[index].currentWidget;
          helper.IconsMap.forEach((k, v) {
            var iconButton = iconbutton.icon as Icon;
            if (v.codePoint == iconButton.icon.codePoint) {
              print('${k}');
            }
          });
        },
        icon: Icon(
          iconData,

output of click first two icon

I/flutter ( 6215): extension
I/flutter ( 6215): face

working demo

enter image description here

full code

import 'package:flutter/material.dart';
import 'package:icons_helper/icons_helper.dart' as helper;

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: ShowData(),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

class ShowData extends StatefulWidget {
  @override
  _ShowDataState createState() => _ShowDataState();
}

class _ShowDataState extends State<ShowData> {
  _showIconGrid() {
    var ls = [
      Icons.extension,
      Icons.face,
      Icons.fastfood,
      Icons.favorite,
      Icons.favorite_border,
      Icons.home,
    ];
    var keyList = [
      GlobalKey(),
      GlobalKey(),
      GlobalKey(),
      GlobalKey(),
      GlobalKey(),
      GlobalKey()
    ];
    return GridView.count(
      crossAxisCount: 8,
      children: List.generate(ls.length, (index) {
        var iconData = ls[index];
        return IconButton(
            key: keyList[index],
            onPressed: () {
              IconButton iconbutton = keyList[index].currentWidget;
              helper.IconsMap.forEach((k, v) {
                var iconButton = iconbutton.icon as Icon;
                if (v.codePoint == iconButton.icon.codePoint) {
                  print('${k}');
                }
              });
            },
            icon: Icon(
              iconData,
            ));
      }),
    );
  }

  @override
  Widget build(BuildContext context) {
    return _showIconGrid();
  }
}
chunhunghan
  • 51,087
  • 5
  • 102
  • 120
0

This isn't directly possible to do in flutter as it requires reflection with something like dart:mirrors, which flutter doesn't support.

To accomplish this you would have to manually map each possible iconData to the associated String.

This method uses a Map created from if-else statements:

_showIconGrid() {
    var ls = [
      Icons.extension,
      Icons.face,
      Icons.fastfood,
      Icons.favorite,
      Icons.favorite_border,
      Icons.home,
    ];

    var iconMap = Map<IconData, String>.fromIterable(
      ls,
      value: (item) {
        if(item == Icons.extension) {
          return "Icons.extension";
        }
        if(item == Icons.face) {
          return "Icons.face";
        }
        ...
        else {
          return "Unknown";
        }
      }
    );

    return GridView.count(
      crossAxisCount: 8,
      children: List.generate(ls.length, (index) {
        var iconData = ls[index];
        return IconButton(
            onPressed: () {
              print(iconMap[iconData]);    
            },
            icon: Icon(
              iconData,
            ));
      }),
    );
  }
Christopher Moore
  • 15,626
  • 10
  • 42
  • 52
0

try this:

return IconButton( tooltip: 'your String'

)

SAJJU
  • 1