Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter using hyphenation with \u00ad in a Text widget and only if applied then replace with a soft hyphen (-)

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
like image 717
th_lo Avatar asked Sep 05 '25 03:09

th_lo


1 Answers

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.

like image 63
Timo Bähr Avatar answered Sep 07 '25 20:09

Timo Bähr