Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Make random parts of a text clickable without textSpan in flutter

Make random parts of a text clickable in flutter without textSpan because when I change the language the order of words also changes. For the textSpan, we know the order of texts matters.

I have user agreement text below in Turkish and Kyrgyz languages. If Locale is in Turkish, Turkish user agreement should be visible, otherwise, Kyrgyz user agreement.

Sample texts:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  1. Кирүүнү басуу менен мен Тейлөө шарттарына макулмун.
  2. Enter’a tıklayarak Hizmet Şartlarını kabul ediyorum

>Solution :

The way I would do it is to somehow mark the clickable part, for example by enclosing it in {}. You can then do this for example:

import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(
      home: Column(
    children: const [
      TextWithLink(
          text: "Кирүүнү басуу менен мен {Тейлөө шарттарына макулмун}"),
      TextWithLink(
          text: "Enter'a tıklayarak {Hizmet Şartlarını} kabul ediyorum")
    ],
  )));
}

class TextWithLink extends StatelessWidget {
  final String text;
  static final regex = RegExp("(?={)|(?<=})");

  const TextWithLink({Key? key, required this.text}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final split = text.split(regex);
    return RichText(
        text: TextSpan(
      children: <InlineSpan>[
        for (String text in split)
          text.startsWith('{')
              ? TextSpan(
                  text: text.substring(1, text.length - 1),
                  style: const TextStyle(
                      decoration: TextDecoration.underline, color: Colors.blue),
                  recognizer: TapGestureRecognizer()
                    ..onTap = () => print("click"),
                )
              : TextSpan(text: text),
      ],
    ));
  }
}

Output:

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading