FlutterUtils
Directory introduction
- 01. Event notification tool class
- 02. Color tools
- 03. Date conversion tools
- 04.File tool class
- 05.Sql database tool class
- 06.Json conversion tools
- 07.Log printing tools
- 08. Screen parameter tools
- 09.Sp lightweight storage tools
- 10. Auxiliary computing tools
- 11. Encryption and decryption tools
- 12.Num format processing tool class
- 13. Equipment parameter acquisition tools
- 14. Image processing tools
- 15. Network processing tools
- 16. Common regular tool classes
- 17. Common tool classes of object
- 18. Verification related tools
- 19. Routing management tools
- 20.Bus event tool class
- 21.Text tool class
- 22.i18 development tools
- 23.Time tool class
- 24.SPI help tools
- 25. Timer auxiliary tools
- 26. Common development tools
- 27. Memory cache tool class
- 28. Clear operation tools
- 29. Tools related to encoding and decoding
- 30. Reflection related tools
- 31. Resource related tools
- 32.Snackbar tools
- 33. Transformation related tools
- 34. Global exception capture tool
- 35. Data analysis tool class
- 36. Byte conversion tool class
- 40. Other related tools
00. Description of the library
- Address of the Library: https://github.com/yangchong211/YCFlutterUtils
00.1 summary of tools in this library
Tool class | Function description |
---|---|
EventBusService | bus event notification tool class, which implements the subscriber mode. For communication between components |
CalculateUtils | Calculate the width and height of the text |
ColorUtils | It mainly converts RGB/ARGB into hexadecimal string Color or Color |
DateFormats | Common Chinese and English date and time conversion formats. Contains most date formats |
DateUtils | Date tool class to obtain date and time, and the conversion operation between various times |
EncryptUtils | Encryption and decryption tools, mainly md5 encryption, base64 encryption and decryption, XOR encryption and decryption, etc |
ExtensionXxx | Extension classes, including int, list, map, set, num, string and other extension classes, have most common operation methods |
TransformUtils | Conversion tool class, including int, string conversion, binary conversion, letter case conversion, etc |
ValidatorUtils | Verification tool class, including common types, pictures, URLs, mailboxes, telephones, resource files, hump naming, etc |
ExtensionXxx | Extension classes, including int, list, map, set, num, string and other extension classes, have most common operation methods |
TransformUtils | Conversion tool class, including int, string conversion, binary conversion, letter case conversion, etc |
FileUtils | The file cache class is mainly used to store and obtain string, Map, Json and other data and write them to the local file |
TransformUtils | Conversion tool class, including int, string conversion, binary conversion, letter case conversion, etc |
AppLocalizations | i18 related, you can set locale to get the string in the language |
ImageUtils | Image tools are mainly responsible for image and base64 conversion, loading network images, switching fillets, circles, etc |
JsonUtils | json transformation tool class is mainly responsible for the transformation between list, map, object and json |
get_it | spi interface implementation separates and decouples the interface (abstract base class) from the concrete implementation |
LogUtils | Log tool class, set log switch, length, filter label and print 5 types of logs |
NumUtils | The num format tool class is mainly responsible for num related processing and conversion operations |
ObjectUtils | The Object superclass tool class is responsible for various Object judgment, length acquisition and other operations |
RegexConstants | Regular constants of common regular expressions. This part mainly refers to AndroidUtils |
RegexUtils | Regular expression tool class, mainly for verification of telephone, ID card, mailbox, ip, network, etc |
ScreenUtils | Screen tool class to obtain the width and height of the screen, pixel density ratio, etc |
SpUtils | sp storage tool class is suitable for storing lightweight data. It is not recommended to store json long strings |
TextUtils | The text tool class mainly deals with string abbreviation, *, comparison, removal and other operations |
TimerUtils | Countdown tool class, set the total countdown time, interval time, start pause, etc |
UrlUtils | url tool class to obtain the host, parameters, verification and other operations of the url |
SystemUtils | System tools, copy content to clipboard, pop up and close soft keyboard, clear data, etc |
OtherUtils | RandomUtils random tool class, SnackUtils, PlatformUtils platform tool class |
MVP | The MVP architecture template of fluent version needs to be improved |
00.2 how to use the library
- Specific documents can be demo s
01. Event notification tool class
- Event bus
- The subscriber mode is usually implemented. The subscriber mode includes two roles: publisher and subscriber.
- The first method: use the map set to store the key as the event eventName and the value as the EventCallback to implement the bus
//Register listening bus _subscription = EventBusService.instance.eventBus.on<EventMessage>().listen((event) { String name = event.eventName; //The switching between front and rear stations has changed if (name == "eventBus1") { var busMessage = event.arguments["busMessage"]; setState(() { message1 = busMessage; }); } }); //send message EventBusService.instance.eventBus.fire(EventMessage( "eventBus1", arguments: {"busMessage": "send out bus Message 1"}, )); //Page destroy clear bus if (_subscription != null) { _subscription.cancel(); _subscription = null; }
- The second method: use StreamController to realize bus event notification
//Register listening messages bus.on("eventBus2", (arg) { var busMessage = arg; setState(() { message2 = "Receive message:" + busMessage; }); }); //send message var arg = "send out bus Message 1"; bus.emit("eventBus2", arg); //Remove message bus.off("eventBus2", (arg) { });
02. Color tools
- Color tool class. It mainly converts RGB or ARGB colors into color objects, hexadecimal color strings, etc.
hexToColor : take#A357D6 Color is converted to hexadecimal Color toColor : take#FF6325 Color or#50A357D6 converted to hexadecimal Color colorString : take color Convert color to string colorString : Check whether the string is hexadecimal
03. Date conversion tools
- Date conversion tool class. It is mainly used to obtain the current date, format the time according to the specified format, and a variety of date formatting tools and methods
getNowDateTime : Get current date return DateTime getYesterday : Get yesterday's date return DateTime getNowUtcDateTime : Get current date return DateTime(utc) getNowDateTimeFormat : Gets the current date and returns the specified format getUtcDateTimeFormat : Gets the current date and returns the specified format isYesterday : Judge whether it was yesterday according to the time getNowDateMs : take#Gets the current millisecond value and returns int getNowDateString : Get the current date string. The default is: yyyy-MM-dd HH:mm:ss,Return string formatDate : Format time, the first field is dateTime,The second option represents the format formatDateString : Format date string, first field, for example:'2021-07-18 16:03:10',The second field, for example:"yyyy/M/d HH:mm:ss" formatDateMilliseconds : Format date and millisecond time. The first field is 1213423143312, for example, and the second field is 1213423143312, for example:"yyyy/M/d HH:mm:ss" getWeekday : obtain dateTime What day is it getWeekdayByMilliseconds : Gets the millisecond value corresponding to the day of the week isToday : Determine whether it is today according to the timestamp isYesterday : Judge whether it was yesterday according to the time
04.File tool class
4.1 file storage tools
- file storage utility class. It mainly stores and obtains String, Json and other files, which are stored in local files
getTempDir : Get a temporary directory(cache),The system can be cleared at any time getAppDocDir : Gets the directory of the application to store files that only it can access. The system clears the directory only when the application is deleted. getAppFile : Initialize the file path. The directory of the application is selected by default readStringDir : Get the data stored in the file and read the directory of the application by default writeJsonFileDir : write in json File, which is written to the directory of the application by default writeStringDir : The string is stored in a file and written to the directory of the application by default clearFileDataDir : Clear cached data deleteFileDataDir : Delete cache file writeJsonCustomFile : write in json Files, custom paths writeStringFile : Use files to store strings and customize paths readStringCustomFile : Get the data stored in the custom path file
4.2 document management tools
- File management tool class. It is mainly used to create different directory paths, create files, or directory paths.
getTempPath : Get the path of the temporary directory on the device. The directory has no backup and is suitable for storing the cache of downloaded files. getAppDocPath : Gets the directory of the application to store files that only it can access. The system clears the directory only when the application is deleted. getStoragePath : The path to the directory where the application can access the top-level storage createDirSync : Create files asynchronously createDir : Create files synchronously createTempDir : Create temporary directory createAppDocDir : Create a directory to get applications
05.Sql database tool class
- To be improved
06.Json conversion tools
- JSON conversion tool class. Common operations of JSON conversion, and gradually improve the mutual conversion of list, map and JSON strings.
printJson : Simple Json Format output printing printJsonEncode : Simple Json Format output printing encodeObj : Will object[value]Convert to JSON character string getObj : transformation JSON String to object getObject : transformation JSON String or JSON mapping[source]To object getObjList : transformation JSON String list[source]To object list getObjectList : transformation JSON String or JSON Mapping list[source]To object list
07.Log printing tools
- Log log printing tool class. For five different types of logs, you can also add tag filtering.
init : Initialization log, custom tag,Is it debug Environment and maximum log length are not required d : Print debug journal e : Print error journal v : Print v journal i : Print info journal w : Print ware Warning log
08. Screen parameter tools
- Screen parameter tool class. Get the width, height, pixel density, status bar and other properties of the screen. Later, improve the adaptation work
screenWidthDp : Current device width dp screenHeightDp : Current device height dp pixelRatio : Pixel density of the device screenWidth : Current device width px = dp * density screenHeight : Current device height px = dp * density statusBarHeight : Status bar height dp Liu Haiping will be higher bottomBarHeight : Bottom safety zone distance dp textScaleFactory : The number of pixels of the font, and the scaling of the font
09.Sp lightweight storage tools
- sp lightweight storage tool. sp mainly stores and obtains int, String, list, map and other data operations.
init : Initialization, must be initialized hasKey : Judge whether it exists key Data putObject : storage object Type data getObject : obtain sp in key of map data putObjectList : storage sp in key of list aggregate getObjectList : obtain sp in key of list aggregate getString : obtain sp in key String of putString : storage sp in key String of getBool : obtain sp in key Boolean value of putBool : storage sp in key Boolean value of getInt : obtain sp in key of int value putInt : storage sp in key of int value getDouble : obtain sp in key of double value putDouble : storage sp in key of double value getStringList : obtain sp in key of list<String>value putStringList : storage sp in key of list<String>value getStringMap : obtain sp in key of map value putStringMap : storage sp in key of map value getDynamic : obtain sp in key of dynamic value getKeys : obtain sp All in key remove : remove sp in key Value of clear : eliminate sp isInitialized : Check initialization forEach : Traversal printing sp of key and value
11. Encryption and decryption tools
- Encryption and decryption tool class. At present, base64 encryption and decryption and md5 encryption are supported. Later, gradually improve more encryption methods
encodeMd5 : md5 Encrypted string, this is irreversible encodeBase64 : Base64 Encrypted string decodeBase64 : Base64 Decrypt string xorBase64Encode : XOR symmetry Base64 encryption xorBase64Decode : XOR symmetry Base64 decrypt
12.Num format processing tool class
- Format processing tool class. It mainly deals with operations related to num format conversion.
isNum : The check string is int still double getIntByValueString : Convert numeric string to int. If the string is not a number, it is converted to 0 getDoubleByValueString : Numeric string to double. If the string is not a number, it is converted to 0 getNumByValueString : Convert numeric string to num,Digital retention x Decimal place getNumByValueDouble : Floating point number retention x Decimal place addNum : Add two numbers (prevent loss of precision) subtractNum : Subtract two numbers (prevent loss of accuracy) multiplyNum : Multiply two numbers (prevent loss of accuracy) divideNum : Divide two numbers (prevent loss of precision) addDecString : Add two numbers (prevent loss of precision) subtractDecString : Subtract two numbers (prevent loss of accuracy) multiplyDecString : Multiply two numbers (prevent loss of accuracy) divideDecString : Divide two numbers (prevent loss of precision)
14. Image processing tools
- Other methods to be improved, such as fillet, circular cutting pictures, and methods to deal with local pictures. Later, improve the methods of obtaining picture attributes, picture compression and various tangent angles.
base64ToImage : take base64 Convert stream to picture fileToBase64 : Will picture file Convert to base64 networkImageToBase64 : Convert web link pictures to base64 assetImageToBase64 : take asset Convert picture to base64 showNetImageWh : Load the network picture and specify the width, height and size. Use default preload loading And error view showNetImageWhError : Load the network picture and specify the width, height and size. Incoming error view showNetImageWhPlaceError : Load the network picture and specify the width, height and size. Incoming preload, error view showNetImageWhClip : Load the network picture, specify the width, height and size, and cut the fillet showNetImageCircle : Load network pictures and cut circular pictures
15. Network processing tools
15.1 network request tools
15.2 Url parsing tool class
- Tool classes related to url parsing
containsTarget : judge url Does the link contain parameters getFirstPath : obtain url First parameter in getUrlHost : obtain url In link host getUrlScheme : obtain url In link scheme getFirstPath : obtain url First parameter in isURL : Returns whether the input matches url Regular expression for
16. Common regular tool classes
- Common regular expressions, learn from the AndroidUtils tool class, and turn java into dart
isMobileSimple : Simple verification of mobile phone number isMobileExact : Accurate verification of mobile phone number isTel : Verify phone number isIDCard15 : Verify ID number 15. isIDCard18 : Simply verify the ID number 18 bits. isIDCard18Exact : Accurate identification ID number 18 bits. isEmail : Verify mailbox isURL : verification URL isZh : Verify Chinese characters isUsername : Verify user name isDate : verification yyyy-MM-dd Date verification in format, taking into account flat leap years isIP : verification IP address match : Determine whether to match regular RegexConstants.REGEX_DOUBLE_BYTE_CHAR : Double byte RegexConstants.REGEX_BLANK_LINE : Blank line RegexConstants.REGEX_QQ_NUM : QQ number RegexConstants.REGEX_CHINA_POSTAL_CODE : Zip code RegexConstants.REGEX_INTEGER : integer RegexConstants.REGEX_POSITIVE_INTEGER : positive integer RegexConstants.REGEX_NEGATIVE_INTEGER : negtive integer RegexConstants.REGEX_NOT_NEGATIVE_INTEGER: Nonnegative integer RegexConstants.REGEX_NOT_POSITIVE_INTEGER: Non positive integer RegexConstants.REGEX_FLOAT : Floating point number RegexConstants.REGEX_POSITIVE_FLOAT : Positive floating point number RegexConstants.REGEX_NEGATIVE_FLOAT : Negative floating point number RegexConstants.REGEX_NOT_NEGATIVE_FLOAT : Nonnegative floating point number RegexConstants.REGEX_NOT_POSITIVE_FLOAT : Non positive floating point number
17. Common tool classes of object
- Object related tool classes are as follows:
isNull : Judge whether the object is null isNullOrBlank : Check whether the data is empty or empty(Empty or contain only spaces) isEmptyString : Determine whether the string is empty isEmptyList : Determine whether the collection is empty isEmptyMap : Determine whether the dictionary is empty isEmpty : judge object Is the object empty isNotEmpty : judge object Is it not empty compareListIsEqual : Compare whether the two sets are the same getLength : obtain object Length of
18. Verification related tools
- Validation related tool classes
isNumericOnly : Check whether the string contains only numbers isAlphabetOnly : Check whether the string contains only letters.(No spaces) isBool : Check whether the string is Boolean isVector : inspect string Is it vector file isImage : Check whether the string is an image file isAudio : Check whether the string is an audio file isVideo : Check whether the string is a video file isTxt : Check whether the string is txt text file isDocument : Check whether the string is doc file isExcel : Check whether the string is excel file isPPT : Check whether the string is ppt file isAPK : Check whether the string is apk file isPDF : Check whether the string is pdf file isHTML : Check whether the string is html file isURL : Check whether the string is url file isEmail : Check whether the string is email file isDateTime : Check whether the string is time isMD5 : Check whether the string is md5 isSHA1 : Check whether the string is sha1 isSHA256 : Check whether the string is sha256 isIPv4 : Check whether the string is ipv4 isIPv6 : Check whether the string is ipv6 isPalindrome : Check whether the string is palindrome isCaseInsensitiveContains : inspect a Include b(Treat large and small initials as the same or interpret). isCaseInsensitiveContainsAny : inspect a Does it contain b or b Does it contain a(Treat large and small initials as the same). isCamelCase : Check the string value for hump case isCapitalize : Check whether the string value is capitalized
19. Routing management tools
21.Text tool class
- Text related tools are as follows:
isEmpty : Judge whether the text content is empty isNotEmpty : Judge whether the text content is not empty startsWith : The judgment string is xx start contains : Determine whether the string contains xx abbreviate : Use dot abbreviation string compare : Compare whether the two strings are the same hammingDistance : Comparing two strings of the same length has several different characters formatDigitPattern : every other x Bit plus pattern. For example, it is used to format bank cards formatSpace4 : Add spaces every 4 digits hideNumber : Hide the middle of mobile phone number n For example, the hidden mobile phone number 13667225184 is 136****5184 replace : Replace data in string split : Cut the string according to the rules and return the array reverse : Reverse string
22.i18 development tools
- In locationextensionstate class: String getString(String id)
- Get language content from different Locales channels. Example: use: VAR name = context getString(“name”);
- Locationextensioncontext class: String getString(String id)
- Get language content from different Locales channels
- How to add language content from different channels. Written before runApp in main function
AppLocalizations.supportedLocales = [ const Locale('en', 'US'), const Locale('pt', 'BR'), const Locale('ja', 'JP'), const Locale('zh', 'CN'), ];
23.Time tool class
24.SPI help tools
- Brief introduction to spi
- Service Locator can separate and decouple the interface (abstract base class) from the concrete implementation, and allow the concrete implementation to be accessed from any location in the App through the interface.
//Step 1 register GetIt serviceLocator = GetIt.instance; getIt.registerSingleton<BusinessService>(new BusinessServiceImpl()); //Step 2 use BusinessService businessService = serviceLocator<BusinessService>(); businessService.noneBusinessPattern(); //Step 3 unbind serviceLocator.resetLazySingleton<BusinessService>();
25. Timer auxiliary tools
- Timer helper class
TimerUtils : Create countdown timer setTotalTime : Set total countdown time setInterval : set up Timer interval startTimer : Start timing Timer updateTotalTime : Reset total countdown time isActive : judge Timer Start pauseTimer : Pause countdown timer cancel : Cancel timer setOnTimerTickCallback : Set the listening of the countdown timer
26. Common development tools
26.1 int extension class: ExtensionInt
- ExtensionInt extension class
isPalindrome : inspect int Is it palindrome isOneAKind : Check that all data has the same value toBinary : transformation int The value is binary toBinaryInt : transformation int The value is binary int fromBinary : transformation int The value is a binary string
26.2 List extension class: ExtensionList
- ExtensionList extension class
toJsonString : take list Convert to json character string getJsonPretty : take list Convert to json String, wrap valueTotal : obtain num Total value of the list(int/double) isNull : Judge whether the object is null isNullOrBlank : Check whether the data is empty or empty(Empty or contain only spaces)
26.3 Map extension class: ExtensionMap
- ExtensionMap extension class [same as set extension class]
toJsonString : take map Convert to json character string getJsonPretty : take map Convert to json String wrap isNull : Judge whether the object is null isNullOrBlank : Check whether the data is empty or empty(Empty or contain only spaces)
26.4 String extension class: ExtensionString
- ExtensionString extension class
isNull : Judge whether the object is null isNullOrBlank : Check whether the data is empty or empty(Empty or contain only spaces) isNumericOnly : Check whether the string contains only numbers isAlphabetOnly : Check whether the string contains only letters.(No spaces) isBool : Check whether the string is Boolean isVector : inspect string Is it vector file isImage : Check whether the string is an image file isAudio : Check whether the string is an audio file isVideo : Check whether the string is a video file isTxt : Check whether the string is txt text file isDocument : Check whether the string is doc file isExcel : Check whether the string is excel file isPPT : Check whether the string is ppt file isAPK : Check whether the string is apk file isPDF : Check whether the string is pdf file isHTML : Check whether the string is html file isURL : Check whether the string is url file isEmail : Check whether the string is email file isDateTime : Check whether the string is time isMD5 : Check whether the string is md5 isSHA1 : Check whether the string is sha1 isSHA256 : Check whether the string is sha256 isIPv4 : Check whether the string is ipv4 isIPv6 : Check whether the string is ipv6 isPalindrome : Check whether the string is palindrome isCaseInsensitiveContains : inspect a Include b(Treat large and small initials as the same or interpret). isCaseInsensitiveContainsAny : inspect a Does it contain b or b Does it contain a(Treat large and small initials as the same). isCamelCase : Check the string value for hump case isCapitalize : Check whether the string value is capitalized
33. Transformation related tools
- Conversion related operation tool classes
toBinary : transformation int The value is binary, for example: 15 => 1111 toBinaryInt : transformation int The value is binary fromBinary : Convert binary to int value capitalize : Every word in the string should be capitalized capitalizeFirst : The first letter of the string is uppercase and the other letters are lowercase removeAllWhitespace : Delete all spaces in the string numericOnly : Extract the numeric value of the string
34. Global exception capture tool
- For fluent global exception capture, you can use: handle_exception
//If used, in the main method, as follows: hookCrash(() { runApp(MainApp()); });
- Capture a printout:
I/flutter ( 9506): yc e — — — — — — — — — — st — — — — — — — — — — — — — I/flutter ( 9506): yc e | handle_exception : e---->MissingPluginException(No implementation found for method getAll on channel plugins.flutter.io/shared_ I/flutter ( 9506): yc e | preferences) I/flutter ( 9506): yc e — — — — — — — — — — ed — — — — — — — — — ---— — I/flutter ( 9506): yc e handle_exception : stack---->
35. Data analysis tool class
- Parsing xml/html data tool class
36. Byte conversion tool class
- ByteUtils conversion related operation tool classes
toBinary : transformation int The value is binary toReadable : Converts a byte array to a readable string toBase64 : Convert byte array to base64 character string fromBase64 : transformation base64 String to byte array clone : Clone byte array same : Judge whether the two bytes are the same extract : Extract data from byte sequence combine : Splice two bytes insert : Inserts a byte at an index remove : Remove bytes at an index
40. Other related tools
40.2 attached tools
- RandomUtils
randomColor : Generates a random integer representing a hexadecimal color randomString : Generates a random string of a specified length or a random length randInt : Generates a random number between the beginning and the end randomElement : Returns a random element from the list
40.3 obtaining platform tools
- PlatformUtils. The tool class can distinguish the platform information by obtaining the platform and setting a value.
final value = PlatformUtils.select( ios: "ios", android: "android", web: "web", fuchsia: "fuchsia", macOS: () => "macOS", windows: () => "windows", linux: () => "linux", ); //As a result, on Android devices, value is: Android
40.4 shear plate tools
- System tools, mainly soft keyboard operation and copying content to the clipboard
copyToClipboard : Copy text content to clipboard hideKeyboard : Hide the soft keyboard. See: TextInputChannel showKeyboard : Display soft keyboard clearClientKeyboard : Clear data
41. Reference projects and blogs
- https://github.com/Blankj/AndroidUtilCode
- https://pub.dev/packages/emote_utils/versions
- https://blog.csdn.net/iotjin/article/details/104881659
- https://cloud.tencent.com/developer/article/1772198
- https://blog.csdn.net/yechaoa/article/details/89845701
- https://blog.csdn.net/aau88497/article/details/102344984
- https://github.com/Sky24n/flustars
- https://github.com/a14n/dart-decimal
- https://pub.dev/packages?q=html_xml_parser