Gesture detection: SelectableText inside ElevatedButton

Issue

I have a problem in Flutter Web with components that are Clickable (ElevatedButton, GestureDetector, etc) and at the same time contains a SelectableText widget inside.

The main problem is that a single click on top of the SelectableText does not trigger the onPressed button callback. Instead, it looks like ‘initiates’ a text selection.

From my point of view, text selection should only be initialized if a double tap, drag start or long tap happens on the text, but not on single tap.

A very simplified version of my problem:


import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      home: Center(
        child: ElevatedButton(
          onPressed: () {
            print('onTap');
          },
          child: Container(
            padding: const EdgeInsets.all(36),
            child: const SelectableText(
              'Select me, but I also want to be clickable!',
              textAlign: TextAlign.center,
              style: TextStyle(
                fontSize: 24,
              ),
            ),
          ),
        ),
      ),
    );
  }
}

enter image description here

Note the padding between the ElevatedButton and the SelectableText

Any tips? ideas?
Thanks in advance

Solution

I understand you are trying your best to mimic the "native web experience" where all texts are selectable, and like you said, "tap and drag start are different", but their differences might be as little as 1 pixel.

If you look at this web page (stack overflow), my user name is clickable, try to drag and select it, you can’t. Now scroll up, below your question, the tags are clickable, try to drag and select on the word "flutter", you can’t…

So honestly, for those texts on buttons, maybe just don’t let them be selectable 😀

But if you insist, there’s onTap event on SelectableText widget as well, so you can fire the same callback as the button, so it doesn’t matter where user clicked.

Answered By – user1032613

Answer Checked By – David Marino (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.