formatTextLink function
void
formatTextLink({
- required TextEditingController controller,
- required TextSelection selection,
Implementation
void formatTextLink({
required TextEditingController controller,
required TextSelection selection,
}) {
String selectionText =
controller.text.substring(selection.start, selection.end);
String placeholder = 'My Link text';
String placeholderEnd = 'https://example.com';
if (controller.text.isNotEmpty && selectionText.isNotEmpty) {
var newText = selectionText;
var beforeText = controller.text.substring(0, selection.start);
var afterText =
controller.text.substring(selection.end, controller.text.length);
newText = '[$newText]($placeholderEnd)';
newText = '$beforeText$newText$afterText';
controller.text = newText;
controller.selection = TextSelection(
baseOffset:
selection.start + 3 + selectionText.length + 'https://'.length,
extentOffset: selection.end + placeholderEnd.length + 3);
} else {
var beforeText = controller.text.substring(0, selection.start);
var afterText =
controller.text.substring(selection.end, controller.text.length);
controller.text = '$beforeText[$placeholder]($placeholderEnd)$afterText';
controller.selection = TextSelection(
baseOffset:
selection.start + 3 + placeholder.length + 'https://'.length,
extentOffset:
selection.end + placeholder.length + 3 + placeholderEnd.length);
}
}