'Flutter Text only break lines at whitespaces
My issue is that flutter breaks Text at non whitespace characters:
How can I tell flutter not to beak text at the "/" but only when it encounters a whitespace?
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
home: Scaffold(
body: Center(
child: Container(
width: 220.0,
child: Text(
'This should not break here x/y/z',
style: TextStyle(fontSize: 30.0),
),
),
),
),
);
}
}
I have been looking into packages like auto_size_text, but found nothing addressing this problem.
Edit:
Working with '\n' is not an option since the length of the text varies,but it always includes the three x/y/z characters divided by slashes at the end.
I would rather not calculate the size of the rendered text in advance to determine whether a newline should be included before x/y/z. That would seem a little heavy, since these are card titles contained in a ListView.
On the web there is no issue, there the text is only broken at whitespaces:
<!DOCTYPE html>
<html>
<body>
<div style="background-color: grey; height: 200px; width: 400px;">
<p style="font-size: 24.0pt;">
This should not break here x/y/z
</p>
</div>
</body>
</html>
Solution 1:[1]
I usually use TextAlign.justify
to fit the text, and to my liking, you can try:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
home: Scaffold(
body: Center(
child: Container(
width: 220.0,
child: Text(
'This should not break here x/y/z',
textAlign: TextAlign.justify,
style: TextStyle(fontSize: 30.0),
),
),
),
),
);
}
}
Also TextAlign.center
not bad.
Solution 2:[2]
https://github.com/flutter/flutter/issues/61081#issuecomment-1103330522
- Replace space with NO-BREAK SPACE
'\u00a0'
where you don't want to break. This forces two characters around it to stay put together in the same line.- Insert ZERO WIDTH NO-BREAK SPACE
'\ufeff'
between the characters you don't want to break. Same as the above but takes no space.- Optionally insert ZERO WIDTH SPACE
'\u200b'
where you want to break. This allows two characters around it to break freely.
To break only around spaces, replace
Text(string)
with
Text(string.split('').join('\ufeff').replaceAll('\ufeff \ufeff', ' '))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | farouk osama |
Solution 2 |