Is there is a way to do hyphenation with \u00ad in a Text widget and only if the hyphenation is applied then it should replace a soft hyphen symbol (-) on the word break?
for example:
Hyphen\u00adation text
should look like if text is not breaking
Hyphenation text
or like this if the text is splitted up in two lines with a (-) symbol
Hyphen-
ation text
I just wrote this StatelessWidget for that purpose:
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
class TextWithHyphenation extends StatelessWidget {
const TextWithHyphenation(
this.data, {
Key? key,
this.style,
}) : super(key: key);
final String data;
final TextStyle? style;
@override
Widget build(BuildContext context) {
return LayoutBuilder(builder: (context, size) {
final String text = data;
final span = TextSpan(text: text, style: style);
final textPainter = TextPainter(
text: span, maxLines: 2, textDirection: ui.TextDirection.ltr)
..layout(maxWidth: size.maxWidth);
final TextSelection selection =
TextSelection(baseOffset: 0, extentOffset: text.length);
final List<TextBox> boxes = textPainter.getBoxesForSelection(selection);
final int lines = boxes.length;
if (lines > 1) {
// The text has more than a line
return Text(text.replaceFirst('\u00ad', '\u00ad-'), style: style);
} else {
return Text(text, style: style);
}
});
}
}
Note, that this only works for one \u00ad
char inside a String resource.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With