flutter_kinetra/lib/kt_utils/kt_string_extend.dart
2025-09-12 14:19:13 +08:00

40 lines
1.0 KiB
Dart
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

extension AssetString on String {
String get ktIcon => "assets/$this";
// 截断字符串并添加省略号
String truncate(int maxLength) {
if (length <= maxLength) return this;
return '${substring(0, maxLength)}...';
}
// 首字母大写
String capitalize() {
if (isEmpty) return this;
return this[0].toUpperCase() + substring(1);
}
// 转为 int失败返回 null
int? toIntOrNull() => int.tryParse(this);
// 转为 double失败返回 null
double? toDoubleOrNull() => double.tryParse(this);
// 判断是否为数字
bool get isNumeric => double.tryParse(this) != null;
// 去除所有空白
String get removeAllWhitespace => replaceAll(RegExp(r'\s+'), '');
}
extension NullString on String? {
bool get isNullString => this == null || (this?.isEmpty ?? false);
// 安全截断
String safeTruncate(int maxLength) {
if (this == null) return '';
return this!.truncate(maxLength);
}
// 安全首字母大写
String get safeCapitalize => (this?.capitalize() ?? '');
}