types.dart 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. import 'dart:ui';
  2. import 'package:fis_common/helpers/string.dart';
  3. class _TrStrInner {
  4. _TrStrInner(String value) {
  5. _value = value;
  6. }
  7. late final String _value;
  8. /// 值
  9. String get value => _value;
  10. @override
  11. int get hashCode => _value.hashCode;
  12. @override
  13. bool operator ==(dynamic other) {
  14. if (other != null && other is _TrStrInner) return value == other.value;
  15. return false;
  16. }
  17. @override
  18. String toString() => value;
  19. }
  20. /// Fis翻译字典值
  21. class FTrStr extends _TrStrInner implements Comparable<String>, Pattern {
  22. /// Fis翻译字典值
  23. ///
  24. /// [value] 翻译值
  25. FTrStr(String value) : super(value);
  26. @override
  27. Iterable<Match> allMatches(String string, [int start = 0]) {
  28. return value.allMatches(string, start);
  29. }
  30. @override
  31. Match? matchAsPrefix(String string, [int start = 0]) {
  32. return value.matchAsPrefix(string, start);
  33. }
  34. @override
  35. int compareTo(dynamic other) {
  36. return value.compareTo(other);
  37. }
  38. }
  39. extension FTrStrExtension on FTrStr {
  40. /// 翻译值
  41. String get t => this.value;
  42. /// 翻译
  43. ///
  44. /// [args] 参数集合
  45. String translate([List<dynamic>? args]) =>
  46. FStringHelper.formart(this.value, args);
  47. }
  48. abstract class ModuleBase implements IPropQueryable {}
  49. /// 属性可查询
  50. abstract class IPropQueryable {
  51. /// 根据字段名获取
  52. dynamic getProp(String propName);
  53. }
  54. class StringMapUtils {
  55. /// 剥取翻译值
  56. ///
  57. /// [key] 字典键
  58. ///
  59. /// [defaultValue] 默认翻译
  60. static FTrStr pickTrStr(Map<String, dynamic> map, String key,
  61. [String? defaultValue]) {
  62. dynamic value = map[key];
  63. if (value == null) value = defaultValue;
  64. if (value == null)
  65. throw UnimplementedError(
  66. 'translation keybook is not complete: Key - $key in some module.');
  67. return FTrStr(value);
  68. }
  69. }
  70. extension FTrMapPickExtension on Map<String, dynamic> {
  71. /// 剥取翻译值
  72. ///
  73. /// [key] 字典键
  74. ///
  75. /// [defaultValue] 默认翻译
  76. FTrStr pick(String key, [String? defaultValue]) =>
  77. StringMapUtils.pickTrStr(this, key, defaultValue);
  78. }
  79. extension LocaleExtensions on Locale {
  80. String toCodeString([String separator = '_']) =>
  81. '${this.languageCode}$separator${this.countryCode ?? ""}';
  82. }
  83. extension StringLocaleExtensions on String {
  84. Locale? toLocale([String separator = '_']) {
  85. if (this.length < 2) return null;
  86. final splited = this.split(separator);
  87. return Locale(splited[0], splited.length > 1 ? splited[1] : null);
  88. }
  89. }