Skip to content

fix: use String#characters instead of substring for truncation in circular charts. #1661

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -154,15 +154,15 @@ String addEllipse(String text, int maxLength, String ellipse, {bool? isRtl}) {
if (isRtl ?? false) {
if (text.contains(ellipse)) {
text = text.replaceAll(ellipse, '');
text = text.substring(1, text.length);
text = text.takeRange(1, text.length);
} else {
text = text.substring(ellipse.length, text.length);
text = text.takeRange(ellipse.length, text.length);
}
return ellipse + text;
} else {
maxLength--;
final int length = maxLength - ellipse.length;
final String trimText = text.substring(0, length);
final String trimText = text.takeRange(0, length);
return trimText + ellipse;
}
}
Expand Down Expand Up @@ -818,6 +818,16 @@ Offset getPerpendicularDistance(Offset startPoint, CircularChartPoint point) {
return increasedLocation;
}

extension on String {
/// Returns a [String] representing the substring of this [String] from the
/// [start] index to the [end] index using the String's [characters] rather
/// than its code units. This ensures that the returned [String] is a valid
/// string and emoji characters are not split into separate characters.
String takeRange(int start, int end) {
return characters.skip(start).take(end - start).join();
}
}

/// To trim the text by given width.
String getTrimmedText(String text, num labelsExtent, TextStyle labelStyle,
{bool? isRtl}) {
Expand All @@ -828,15 +838,15 @@ String getTrimmedText(String text, num labelsExtent, TextStyle labelStyle,
final int textLength = text.length;
if (isRtl ?? false) {
for (int i = 0; i < textLength - 1; i++) {
label = '...${text.substring(i + 1, textLength)}';
label = '...${text.takeRange(i + 1, textLength)}';
size = measureText(label, labelStyle).width;
if (size <= labelsExtent) {
return label == '...' ? '' : label;
}
}
} else {
for (int i = textLength - 1; i >= 0; --i) {
label = '${text.substring(0, i)}...';
label = '${text.takeRange(0, i)}...';
size = measureText(label, labelStyle).width;
if (size <= labelsExtent) {
return label == '...' ? '' : label;
Expand Down