Skip to content

Instantly share code, notes, and snippets.

@putraxor
Created April 25, 2018 05:59
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save putraxor/03ad59c117122b74155a77e5c101ff2a to your computer and use it in GitHub Desktop.
Save putraxor/03ad59c117122b74155a77e5c101ff2a to your computer and use it in GitHub Desktop.
Flutter rich text view with clickable hyperlink
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart' as launcher;
///TODO: check performance impact bro !!!
class LinkTextSpan extends TextSpan {
LinkTextSpan({TextStyle style, String url, String text})
: super(
style: style,
text: text ?? url,
recognizer: new TapGestureRecognizer()
..onTap = () => launcher.launch(url));
}
class RichTextView extends StatelessWidget {
final String text;
RichTextView({@required this.text});
bool _isLink(String input) {
final matcher = new RegExp(
r"(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)");
return matcher.hasMatch(input);
}
@override
Widget build(BuildContext context) {
final _style = Theme.of(context).textTheme.body2;
final words = text.split(' ');
List<TextSpan> span = [];
words.forEach((word) {
span.add(_isLink(word)
? new LinkTextSpan(
text: '$word ',
url: word,
style: _style.copyWith(color: Colors.blue))
: new TextSpan(text: '$word ', style: _style));
});
if (span.length > 0) {
return new RichText(
text: new TextSpan(text: '', children: span),
);
} else {
return new Text(text);
}
}
}
@ASemeniuk
Copy link

How about calling the dispose() method of TapGestureRecognizer, huh? Everyone seems to just ignore that https://api.flutter.dev/flutter/painting/TextSpan/recognizer.html.
Ridiculous.

@gazialankus
Copy link

@ASemeniuk
Copy link

ASemeniuk commented Aug 28, 2019

It's surprising to what extent you had to go (reading docs for some unrelated classes) in order to justify the unwillingness to implement the correct architectural aproach. Besides, the link provides incorrect information, which you may quickly check yourself by looking at the source code of TapGestureRecognizer class. This class does define a deadline (100ms duration):

TapGestureRecognizer({ Object debugOwner }) : super(deadline: kPressTimeout, debugOwner: debugOwner);

const Duration kPressTimeout = Duration(milliseconds: 100);

and thus creates a Timer object:

if (deadline != null)
        _timer = Timer(deadline, () => didExceedDeadlineWithEvent(event));

which needs to be stopped in dispose() method:

  @override
  void dispose() {
    _stopTimer();
    super.dispose();
  }

  void _stopTimer() {
    if (_timer != null) {
      _timer.cancel();
      _timer = null;
    }
  }

So, the correct approach is to manage tap recognizer outside of the TextSpan. Exactly the way official documentation states (see the link above).

@gazialankus
Copy link

Sorry this and the other were the two google results and I thought I'd tie the knot between the two. It seems we should submit an issue report for flutter gallery then!

@mwawrusch
Copy link

No need to be rude though. Thank you Ardiansyan for providing helpful code.

@tedhenry100
Copy link

@ASemeniuk your comments are the rudest comments that I've read in quite a while. Shameful behaviour.

@ASemeniuk
Copy link

Sorry, everyone, I had a very bad day back then. After reading like 10 different sources with the same mistake over and over (where people were 100% positive they knew what they were doing) and being unable to find the correct solution I was looking for (about using multiple GestureRecognizers in ListView), I just wanted to share my pain with others. Not happy about the result myself...

@rfogar2
Copy link

rfogar2 commented Jun 9, 2020

Wonder if there is a way to make this work with newline characters as well. Doing

    final words = text.split(' ').split('\n');

would get the links right, but would lose the structure of the original text.

@vashisth00
Copy link

lol this was a nice thread good code @ASemeniuk

@vashisth00
Copy link

@rfogar2 no that is wrong you cannot specify split('').split

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment