Line data Source code
1 : library flutter_guid; 2 : 3 : import 'package:flutter_guid/FlutterGuidError.dart'; 4 : import 'package:uuid/uuid.dart'; 5 : import 'package:validators/validators.dart'; 6 : 7 : /// Class that emulates as closely as possible the C# Guid type. 8 : class Guid { 9 : 10 : static const String _defaultGuid = "00000000-0000-0000-0000-000000000000"; 11 : 12 : /// The Guid whose value is the default sequence of characters that represent a 'zero-value' UUID in .Net "00000000-0000-0000-0000-000000000000" 13 2 : static Guid get defaultValue => new Guid(_defaultGuid); 14 : 15 : String _value; 16 : 17 : /// Constructor, expects a valid UUID and will throw an exception if the value provided is invalid. 18 1 : Guid(String v) { 19 1 : _failIfNotValidGuid(v); 20 1 : _value = v; 21 : } 22 : 23 : /// Generates a new v4 UUID and returns a GUID instance with the new UUID. 24 1 : static Guid get newGuid { 25 3 : return new Guid(Uuid().v4()); 26 : } 27 : 28 : /// Checks whether a value is a valid Guid 29 : /// Returns false if 'guid' is null or has an invalid value 30 : /// Returns true if guid is valid 31 1 : static bool isValid(Guid guid){ 32 : if(guid == null){ 33 : return false; 34 : }else{ 35 2 : return isUUID(guid.value); 36 : } 37 : } 38 1 : _failIfNotValidGuid(String v) { 39 1 : if (v == null || v.isEmpty) { 40 : v = _defaultGuid; 41 : } 42 2 : final isInvalid = isUUID(v) == false; 43 : if(isInvalid){ 44 2 : throw new FlutterGuidError("Value '$v' is not a valid UUID"); 45 : } 46 : } 47 : 48 : /// Gets the UUID value contained by the Guid object as a string. 49 1 : String get value { 50 3 : if (_value == null || _value.isEmpty) { 51 : return _defaultGuid; 52 : } else { 53 1 : return _value; 54 : } 55 : } 56 : 57 : /// Performs a case insensitive comparison on the UUIDs contained in two Guid objects. 58 : /// Comparison is by value and not by reference. 59 1 : bool operator ==(other) { 60 5 : return this.value.toLowerCase() == other.toString().toLowerCase(); 61 : } 62 : 63 : 64 : /// Returns the hashCode. 65 0 : @override 66 : int get hashCode { 67 0 : return super.hashCode; 68 : } 69 : 70 : /// Gets the UUID value contained by the Guid object as a string. 71 1 : @override 72 : String toString() { 73 1 : return value; 74 : } 75 : }