common_expand.dart 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import 'dart:ui';
  2. extension HexColor on String {
  3. Color get color => toColor();
  4. Color toColor() {
  5. String hex = replaceAll('#', '');
  6. if (hex.length == 6) {
  7. hex = 'FF$hex';
  8. }
  9. return Color(int.parse(hex, radix: 16));
  10. }
  11. }
  12. extension DoubleExtension on double {
  13. String toFormattedString(int fractionDigits) {
  14. if (this == toInt()) {
  15. return toInt().toString();
  16. } else {
  17. return toStringAsFixed(fractionDigits);
  18. }
  19. }
  20. double toFormattedDouble(int fractionDigits) {
  21. return double.parse(toStringAsFixed(fractionDigits));
  22. }
  23. }
  24. extension FutureMap<T> on Future<T> {
  25. Future<R> map<R>(R Function(T) transform) {
  26. return then(transform);
  27. }
  28. }
  29. extension TrimAllExtension on String {
  30. String trimAll() {
  31. return replaceAll(RegExp(r'\s+'), '');
  32. }
  33. String trimAndReduceSpaces() {
  34. return trim().replaceAll(RegExp(r'\s+'), ' ');
  35. }
  36. }
  37. // RegExp regExp = RegExp(r"(\d+\.?\d*)(元/月)");
  38. extension PriceExtractionExtension on String {
  39. /// 提取金额部分(如 "32元/月" → "32")
  40. String extractAmount() {
  41. final match = RegExp(r'(\d+\.?\d*)').firstMatch(this);
  42. return match?.group(1) ?? ''; // 返回数字部分,失败时返回空字符串
  43. }
  44. /// 提取单位部分(如 "32元/月" → "元/月")
  45. String extractUnit() {
  46. final match = RegExp(r'(\d+\.?\d*)(.*)').firstMatch(this);
  47. return match?.group(2) ?? ''; // 返回单位部分,失败时返回空字符串
  48. }
  49. /// 同时提取金额和单位(返回元组)
  50. (String amount, String unit) extractAmountAndUnit() {
  51. final match = RegExp(r'(\d+\.?\d*)(.*)').firstMatch(this);
  52. return (
  53. match?.group(1) ?? '', // 金额
  54. match?.group(2) ?? '' // 单位
  55. );
  56. }
  57. }