skip to Main Content

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);
}

2

Answers


  1. 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.

    Login or Signup to reply.
  2. 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(),
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search