Trần Đức Tâm
Trần Đức Tâm

Reputation: 4453

How to make GestureDetector also work when touch empty space in Flutter

I have 2 Text widget inside an GestureDetector. The onTap callback only notify when I touch on the Text but not the empty space inside my Container. How to make this notify like I touch on a button?

+------------------------------------------------+
| Very very very long long ◎ng long text view   |
| Short ◎xt                   ⦿                |
+------------------------------------------------+

My source code:

ListView.separated(
  itemCount: _listModel.length,
  padding: EdgeInsets.only(left: NOTIFICATION_LEFT_SPACE),
  separatorBuilder: (context, index) => Divider(),
  itemBuilder: (BuildContext context, int index) => GestureDetector(
    child: Container(
      child: Hero(
        tag: _listModel[index].title,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Text('Very very very long long long long text view'),
            SizedBox(height: 10),
            Text('Short text')
          ],
        ),
      ),
    ),
    onTap: () {
      print('Tapped');
    },
  ),
)

Upvotes: 51

Views: 13027

Answers (2)

snghnishant
snghnishant

Reputation: 31

I have found a workaround for this. Provide a box decoration to the container wrapped by the GestureDetector and in the box decoration provide a color: Colors.transparent. This will replace the whitespace of the container with a transparent background so UI stays the same and onTap will be also functional on clicking the whitespace. See example code snippet.

 return GestureDetector(
  onTap: () {
    onClick();
  },
  child: Container(
    decoration: BoxDecoration(color: Colors.transparent),
    height: 120.0,
    margin: margin != null
        ? EdgeInsets.all(margin)
        : EdgeInsets.symmetric(horizontal: 35.0, vertical: 15.0),
    // margin: EdgeInsets.all(0),
    child: ...)

Upvotes: 3

Darshan
Darshan

Reputation: 11679

You can use behavior: HitTestBehavior.opaque property of GestureDetector widget, that helps to tap on the placeholder inside Container even if Container widget doesn't have any child.

GestureDetector(
                behavior: HitTestBehavior.opaque,
                child: Container(
                  child: Hero(
                    tag: 'test',
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Text('Very very very long long long long text view'),
                        SizedBox(height: 10),
                        Text('Short text')
                      ],
                    ),
                  ),
                ),
                onTap: () {
                  print('Tapped');
                },
              ),

Upvotes: 126

Related Questions