Line data Source code
1 : import 'package:flutter/services.dart'; 2 : import 'package:folly_fields/util/mask_text_input_formatter.dart'; 3 : import 'package:folly_fields/validators/abstract_validator.dart'; 4 : 5 : /// 6 : /// 7 : /// 8 : class ColorValidator extends AbstractParserValidator<Color> { 9 : /// 10 : /// 11 : /// 12 1 : ColorValidator() 13 1 : : super( 14 1 : <TextInputFormatter>[ 15 1 : MaskTextInputFormatter( 16 : mask: 'AAAAAAAA', 17 1 : filter: <String, RegExp>{ 18 1 : 'A': RegExp('[0-9,A-F,a-f]'), 19 : }, 20 : ), 21 : ], 22 : ); 23 : 24 : /// 25 : /// 26 : /// 27 1 : @override 28 : String format(Color value) => 29 4 : value.value.toRadixString(16).toUpperCase().padLeft(8, '0'); 30 : 31 : /// 32 : /// 33 : /// 34 1 : @override 35 : String strip(String value) => value; 36 : 37 : /// 38 : /// 39 : /// 40 1 : @override 41 1 : bool isValid(String value) => valid(value) == null; 42 : 43 : /// 44 : /// 45 : /// 46 1 : @override 47 : Color? parse(String? text, [int? defaultColor]) { 48 1 : if (text == null || text.isEmpty) { 49 1 : return defaultColor == null ? null : Color(defaultColor); 50 : } else { 51 : try { 52 1 : if (!text.startsWith('0x')) { 53 3 : text = text.replaceAll('#', '').trim().toUpperCase(); 54 : 55 2 : if (text.length < 3) { 56 1 : throw Exception('Length less than 3.'); 57 : } 58 : 59 2 : if (text.length == 3) { 60 11 : text = text[0] + text[0] + text[1] + text[1] + text[2] + text[2]; 61 : } 62 : 63 2 : if (text.length == 4) { 64 2 : text = text[0] + 65 2 : text[0] + 66 2 : text[1] + 67 2 : text[1] + 68 2 : text[2] + 69 2 : text[2] + 70 2 : text[3] + 71 1 : text[3]; 72 : } 73 : 74 2 : if (text.length == 6) { 75 1 : text = 'FF$text'; 76 : } 77 : 78 2 : if (text.length > 8) { 79 1 : text = text.substring(0, 8); 80 : } 81 : 82 1 : text = '0x$text'; 83 : } 84 : 85 2 : return Color(int.parse(text)); 86 1 : } on Exception catch (_) { 87 1 : return defaultColor == null ? null : Color(defaultColor); 88 : } 89 : } 90 : } 91 : 92 : /// 93 : /// 94 : /// 95 1 : @override 96 1 : String? valid(String? value) => parse(value) == null ? 'Cor inválida.' : null; 97 : }