ronjb / selectable

A Flutter widget that enables text selection over all the text widgets it contains
MIT License
18 stars 13 forks source link

tap to get index of text. #21

Open vishalpatel1327 opened 9 months ago

vishalpatel1327 commented 9 months ago

I love the package. is that any way to get an index when I tap on any text?

for ex, I highlighted one Word.

then when I single tap on that highlighted word. need to open the information of that word. so if you guys can help me to get the index of that text I can do that feature.

ronjb commented 9 months ago

In main.dart of the example app, on line 148 you'll see this:

    final selection = controller?.getSelection();
    final startIndex = selection?.startIndex;
    final endIndex = selection?.endIndex;

It gets the selection from the controller, and from that you can get the startIndex and endIndex.

vishalpatel1327 commented 9 months ago

@ronjb That's I agree but how can I get something like onTaplistener?

for ex. I highlighted consectetur ,

now when I just single-tap on it. need to open some description for it. so onTap of that word if I get the index of where I tap. I can use that index to make something achievable.

image

it can be achieved in SelectableText but that default widget don't have feature like "selectable" have,

image

Ronakmewara commented 8 months ago

The identical problem is happening to me, @vishalpatel1327. Tell us as soon as you have the answer.

ronjb commented 8 months ago

@vishalpatel1327,

Just to make sure I understand what you're asking. After a word is selected, for example "consectetur", if that word is tapped you want to do something, for example, open a dialog with the word's description. Is that what you are asking?

If so, you can do something like that by 1) wrapping Selectable in a Stack, 2) using the selection rects provided via the getSelection()?.rects method on SelectableController to provide tap targets to listen to.

For example, you could modify the example app like so:

1) Update the _selectionChangedListener to call setState for every selection change:

  void _selectionChangedListener() {
    if (mounted) {
      setState(() {
        _isTextSelected = _selectionController.isTextSelected;
      });
    }
  }

2) Wrap Selectable in a Stack and render InkWell widgets over selection rects to listen for taps:

Stack(
  children: [
    Selectable(...),
    ..._selectionController.getSelection()?.rects?.map((r) {
          return Positioned.fromRect(
              rect: r,
              child: InkWell(onTap: () => print('onTap: $r')));
        }) ??
        [],
  ],
),

Does this make sense, and answer your question?