Home > Software design >  Flutter Gesturedetector return value of ontapped widget
Flutter Gesturedetector return value of ontapped widget

Time:12-18

I have a list:

List<String> myNumbers = ['1', '2', '3']

Above mentioned list is being used to populate Wrap widget nested with text widgets:


    Widget clickArea(List<String> mynumbershere) {
        return Directionality(
          textDirection: TextDirection.rtl,
          child: Wrap(
            children: <Widget>[
              for (int i = 0; i < mynumbershere.length; i  )
                Container(
                  margin: const EdgeInsets.all(5.0),
                  child: GestureDetector(
                    onTap: () {
                      print('hello');
                      print('How do I return the textvalue of the clicked text widget?');
                    },
                    child: Text(
                      mylettershere[i],
                      style: GoogleFonts.secularOne(fontSize: 72),
                    ),
                  ),
                )
            ],
          ),
        );
       }

How do I return (retrieve value of the clicked widget) inside onTap of the GestureDetector? I was thinking thinking the following would do the trick, but it's not working.

onTap: (value) {
  print(value);
}

CodePudding user response:

Well, since you iterate over it using a for loop, each one will be executed at it's own i index, so you can do this:

   onTap: () {
    final currentText = mynumbershere[i]; 
    print(currentText);
   },

now every one will print it's value.

CodePudding user response:

Although your for loop is correct I recommend this way:

children: mynumbershere
      .map((value) => Container(
            margin: const EdgeInsets.all(5.0),
            child: GestureDetector(
              onTap: () {
                print('$value');
              },
              child: Text(
                value,
                style: GoogleFonts.secularOne(fontSize: 72),
              ),
            ),
          ))
      .toList(),
  • Related