diff --git a/example/lib/data/extension/example_string_ext.dart b/example/lib/data/extension/example_string_ext.dart index 175c227..9fff6ea 100644 --- a/example/lib/data/extension/example_string_ext.dart +++ b/example/lib/data/extension/example_string_ext.dart @@ -20,6 +20,11 @@ class _ExampleStringExtState extends State { title: Text('18888888888'), subtitle: Text('18888888888'.phone), ), + ListTile( + leading: Chip(label: Text('.securePhone')), + title: Text('18888888888'), + subtitle: Text('18888888888'.securePhone), + ), ], ), ); diff --git a/lib/extension/string_extension.dart b/lib/extension/string_extension.dart index 20ddbf7..37749d8 100644 --- a/lib/extension/string_extension.dart +++ b/lib/extension/string_extension.dart @@ -1,10 +1,31 @@ extension PhoneExt on String { + List get _parsePhone { + if (this.length < 11) + return []; + else + return [ + this.substring(0, 3), + this.substring(3, 7), + this.substring(7, 11), + ]; + } + + bool get _validPhone => _parsePhone.isNotEmpty; + + ///电话号码加分隔线 + /// + ///example 18888888888 => 188-8888-8888 String get phone { - ///电话号码加分隔线 - return (this.substring(0, 3) + - '-' + - this.substring(3, 7) + - '-' + - this.substring(7, 11)); + if (!_validPhone) + return this; + else + return '${_parsePhone[0]}-${_parsePhone[1]}-${_parsePhone[2]}'; + } + + String get securePhone { + if (!_validPhone) + return this; + else + return '${_parsePhone[0]}****${_parsePhone[2]}'; } }