我想在某个字符长度后将省略号添加到字符串中,如果字符串长度不超过字符预设的字符长度,则不应添加省略号(...)。
如何使用Dart语言实现这一目标?
答案 0 :(得分:10)
您可以使用replaceRange
方法。
var text = 'Hello World!';
var r = text.replaceRange(7, text.length, '...');
print(r); // -> Hello W...
答案 1 :(得分:3)
您可以在字符串上使用扩展名:
extension StringExtension on String {
String truncateTo(int maxLenght) =>
(this.length <= maxLenght) ? this : '${this.substring(0, maxLenght)}...';
}
然后
'My Very Long Text'.truncateTo(7); // My Very...
答案 2 :(得分:2)
创建 extensions.dart 文件。
.woocommerce-error {
display: none;
}
将此用作自定义扩展。
用法
String truncateString(String data, int length) {
return (data.length >= length) ? '${data.substring(0, length)}...' : data;
}
答案 3 :(得分:0)
用以下容器包装“文本”小部件
请:阅读下面代码中的注释行
class TruncatedText extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Container(
//Here you can control the width of your container ..
//when text exceeds it will be trancated via elipses...
width: 130.0,
child: Text('I have a trancated text',
style: TextStyle(fontSize: 20),
softWrap: false,
overflow: TextOverflow.ellipsis,
),
),
);
}
}
编辑:
您可以使用此纯飞镖代码,因为原始解决方案适用于Flutter
void main() {
String to_be_truncated = "Dart is excellent but flutter is awesome";
int truncateAt = to_be_truncated.length-1;//if you use to_be_truncated.lengh no truncation will happen
String elepsis = "..."; //define your variable truncation elipsis here
String truncated ="";
if(to_be_truncated.length > truncateAt){
truncated = to_be_truncated.substring(0,truncateAt-elepsis.length)+elepsis;
}else{
truncated = to_be_truncated;
}
print(truncated);
}
答案 4 :(得分:0)
您可以执行以下操作:
String truncateWithEllipsis(int cutoff, String myString) {
return (myString.length <= cutoff)
? myString
: '${myString.substring(0, cutoff)}...';
}
答案 5 :(得分:0)
以下方法建立在具有这些优势的先前答案的基础上:
extension StringExtension on String {
/// Truncate a string if it's longer than [maxLength] and add an [ellipsis].
String truncate(int maxLength, [String ellipsis = "…"]) => length > maxLength
? '${substring(0, maxLength - ellipsis.length)}$ellipsis'
: this;
}