Created
January 24, 2020 13:46
-
-
Save AlexVegner/b14b6092d2722a40968b415cc5bd306c to your computer and use it in GitHub Desktop.
dart_extension.dart
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// Example 1 | |
/// Enum extension | |
enum NetworkState { | |
unknown, | |
connected, | |
disconnected, | |
} | |
/// NetworkStateExtension | |
extension NetworkStateExt on NetworkState { | |
static const networkStateNames = [ | |
'UNKNOWN', | |
'CONNECTED', | |
'DISCONNECTED', | |
]; | |
static NetworkState parse(dynamic value) { | |
if (value is String) { | |
final index = networkStateNames.indexOf(value); | |
if (index > -1) { | |
return NetworkState.values[index]; | |
} | |
} else if (value is int) { | |
return NetworkState.values[value]; | |
} | |
throw 'not found'; | |
} | |
String get name => networkStateNames[index]; | |
String getName() { | |
return networkStateNames[index]; | |
} | |
} | |
/// Example 1 | |
/// UserEntity extension | |
class UserEntity { | |
final String name; | |
final String email; | |
final int age; | |
UserEntity({this.name, this.email, this.age}); | |
} | |
extension UserEntityExt on UserEntity { | |
UserEntity copyWith({String name, String email, int age}) => UserEntity( | |
name: name ?? this.name, | |
email: email ?? this.email, | |
age: age ?? this.age, | |
); | |
String description() { | |
return '$name, $email, $age'; | |
} | |
} | |
void main() { | |
final networkState = NetworkStateExt.parse('CONNECTED'); | |
print(networkState.name); | |
final u1 = UserEntity(name: 'Alex', age: 35); | |
print(u1.description()); | |
final u2 = u1.copyWith(name: 'Eugene'); | |
print(u2.description()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment