onPressUrlPattern method

TapGestureRecognizer onPressUrlPattern()

This function returns a TapGestureRecognizer that launches a URL if it matches a specified pattern.

Returns: A TapGestureRecognizer object is being returned.

Implementation

TapGestureRecognizer onPressUrlPattern() {
  return TapGestureRecognizer()
    ..onTap = () async {
      final regexp = RegExp(patternMatched.pattern).firstMatch(match);
      final url = regexp?.group(2);
      if (url != null) {
        final shouldOpen = await showDialog<bool>(
          context: context,
          builder: (context) {
            return AlertDialog(
              title: const Text('Nixy'),
              content: Text('Do you want to open $url?'),
              actions: [
                ElevatedButton(
                  onPressed: () => Navigator.pop(context, false),
                  child: const Text(
                    'Cancel',
                  ),
                ),
                ElevatedButton(
                  onPressed: () async {
                    Navigator.pop(context, true);
                  },
                  child: const Text('Open url'),
                )
              ],
            );
          },
        );

        if (shouldOpen != null && shouldOpen) {
          final uri = Uri.parse(url);
          final canLaunch = await canLaunchUrl(uri);

          if (canLaunch) {
            await launchUrl(uri);
          }
        }
      }
    };
}