| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687 |
- import 'dart:ui';
- extension HexColor on String {
- Color get color => toColor();
- Color toColor() {
- String hex = replaceAll('#', '');
- if (hex.length == 6) {
- hex = 'FF$hex';
- }
- return Color(int.parse(hex, radix: 16));
- }
- }
- extension BoolExtension on bool? {
- bool get isTrue => this == true;
- bool get isFalse => this == false;
- }
- extension StringExtension on String? {
- String get orEmpty => this ?? '';
- }
- extension DurationExtension on double? {
- String toFormattedDuration() {
- if (this == null) return '';
- int totalSeconds = (this!).round();
- if (totalSeconds < 60) {
- return '${totalSeconds}s';
- } else if (totalSeconds < 3600) {
- int minutes = totalSeconds ~/ 60;
- int seconds = totalSeconds % 60;
- return '${minutes}m${seconds}s';
- } else {
- int hours = totalSeconds ~/ 3600;
- int minutes = (totalSeconds % 3600) ~/ 60;
- int seconds = totalSeconds % 60;
- return '${hours}h${minutes}m${seconds}s';
- }
- }
- }
- extension StringExtensions on String {
- String replacePlaceholders(List<dynamic> replacements) {
- var result = this;
- for (var replacement in replacements) {
- if (replacement is String) {
- result = result.replaceFirst('%s', replacement);
- } else if (replacement is int) {
- result = result.replaceFirst('%d', replacement.toString());
- }
- }
- return result;
- }
- }
- extension FileSizeExtension on int {
- String toReadableSize() {
- String format(double value) {
- String result = value.toStringAsFixed(2);
- result = result.replaceAll(RegExp(r'0*$'), ''); // 去除多余的零
- result = result.replaceAll(RegExp(r'\.$'), ''); // 如果最后是小数点,则去除
- return result;
- }
- if (this < 1024) {
- return '$this B';
- } else if (this < 1024 * 1024) {
- return '${format(this / 1024)} KB';
- } else if (this < 1024 * 1024 * 1024) {
- return '${format(this / (1024 * 1024))} MB';
- } else {
- return '${format(this / (1024 * 1024 * 1024))} GB';
- }
- }
- }
- extension DurationFormatting on Duration {
- String toFormattedString() {
- String twoDigits(int n) => n.toString().padLeft(2, '0');
- String hours = twoDigits(inHours);
- String minutes = twoDigits(inMinutes.remainder(60));
- String seconds = twoDigits(inSeconds.remainder(60));
- return [if (inHours > 0) hours, minutes, seconds].join(':');
- }
- }
|