Home > Mobile >  how to check which element was tapped in flutter and dat
how to check which element was tapped in flutter and dat

Time:09-16

I created a list of widgets. What I would like to do is to get the index of the widget that is being tapped. I wrapped the widget in gesture detection, and I would like to print the index of the widget which is being tapped

This is a widget I created:

class Tile extends StatelessWidget {
  final Color color;
  const Tile({Key? key,required this.color}) : super(key: key);

  sayhello(int idd){
    print("Hello from the tile file$idd");
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      child: Container(
        width: 30,
        height: 31,
        color: color,
      ),
    );
  }
}

This is the file where it is being used:

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  List<Widget> list = [
    Tile(color: Colors.black26),
    Tile(color: Colors.cyanAccent),
    Tile(color: Colors.deepOrange),
    Tile(color: Colors.tealAccent),
    Tile(color: Colors.purpleAccent),
    Tile(color: Colors.yellowAccent),
    Tile(color: Colors.black),
  ];
  Color color=Colors.amber;

  void _incrementCounter() {
    setState(() {
      if(true)
        {
          list[0]=Container(
            child: Text('HN'),
            color: Colors.deepOrange,
          );
        }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        children:[
          Row(
            children: [
              list[0],
              list[1],
              list[2],
            ],
          ),
          Row(
            children: [
              list[3],
              list[4],
              list[5],
            ],
          ),
        ]
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }
}

I created a list of my widget and added the gestureDetector. I want to get the index of the widget which is being tapped.

CodePudding user response:

I recommend you to use widget key.

Then you can print it on widget tap.

Code:

  1. Tile widget

.

GestureDetector(
          onTap: () {
            print(
              key.toString(),
            );
          },
          child: Container(
            width: 30,
            height: 31,
            color: color,
          ),
        ),
  1. Calling Tile widget

     List<Widget> list = [
     Tile(
       color: Colors.black26,
       key: Key('tile_black'),
     ),
     Tile(
       color: Colors.cyanAccent,
       key: Key('cyan_accent'),
     ),
    

    ];

  • Related