FlutterUtilsThe most complete tool class in the whole network
catalogue
- 01. Event notification Bus class
- 02. Color The Color tool class
- 03. Date conversion tool class
- 04.File tool class
- 05.Sql database tool class
- 06.Json conversion tool class
- 07.Log Log printing tool class
- 08. Screen parameter tool class
- 09.Sp lightweight storage tool class
- 10. Auxiliary computing tools
- 11. Encryption and decryption tool classes
- 12.Num format processing tool class
- 13. Tool class for obtaining device parameters
- 14. Image processing tools
- 15. Network processing tools
- 16. Common regular tool class
- 17.Object Common utility class
- 18. Verify related tool classes
- 19. Route management tools
- 20.Bus event utility class
- 21.Text The Text utility class
- 22. I18 Extension tool class
- 23.Time Tool class
- 24.SPI help tool class
- 25. Timer helper class
- 26. Common extension tool classes
- 27. Memory cache tool class
- 28. Clear the operation tool class
- 29. Codec related tools
- 30. Reflection related tool classes
- 31. Resource related tool classes
- 32. Snackbar tools
- 33. Transform related tool classes
- 34. Global exception catching tool
- 35. Parse data utility class
- 36. Byte conversion tool class
- 40. Other related tool classes
00. Description of the library
- The library address: github.com/yangchong21…
00.1 Summary of the library tool classes
Utility class | Functional specifications |
---|---|
EventBusService | Bus event notification utility class that implements the subscriber mode. Used to communicate between components |
CalculateUtils | Calculate the width and height of the text |
ColorUtils | Convert RGB/ARGB to hexadecimal string Color or Color |
DateFormats | Common Chinese, English date time conversion format. Contains most date formats |
DateUtils | Date tool class, get date and time, conversion operations 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, etc., have most common operations |
TransformUtils | Conversion tool class, including int, string conversion binary, letter case conversion and so on |
ValidatorUtils | Check tool class, including common types, images, URL, mailbox, phone, resource file, camel name and other check |
ExtensionXxx | Extension classes, including int, list, map, set, num, string, etc., have most common operations |
TransformUtils | Conversion tool class, including int, string conversion binary, letter case conversion and so on |
FileUtils | File cache class, mainly to store and get string, Map, Json data, write to the local file |
TransformUtils | Conversion tool class, including int, string conversion binary, letter case conversion and so on |
AppLocalizations | I18, you can set the locale, get the string in the language |
ImageUtils | Image tool class, mainly responsible for image and base64 transformation, loading network images, switching round corners, circles and so on |
JsonUtils | Json conversion tool class, is mainly responsible for list, map, object and JSON conversion between |
get_it | The SPI interface implementation separates and decouples the interface (abstract base class) from the concrete implementation |
LogUtils | Log tool, set log switch, log length, filter labels, and print five types of logs |
NumUtils | Num format tool class, mainly responsible for Num related processing and conversion operations |
ObjectUtils | Object superclass tool class, responsible for various Object judgment, obtain the length of the operation |
RegexConstants | Regular constants for common regular expressions. Refer to AndroidUtils for this section |
RegexUtils | Regular expression tool class, mainly telephone, ID, mailbox, IP, network and other verification |
ScreenUtils | Screen tool class to get the width and height of the screen, as well as the pixel density ratio |
SpUtils | Sp storage tool class, suitable for storing lightweight data, do not recommend to store JSON long string |
TextUtils | Text tool class, mainly handle string thumbnail, *, compare, remove and other operations |
TimerUtils | Down timer tool class, set the total countdown time, interval time, start pause, etc |
UrlUtils | Url tool class, get url host, parameters, verification and other operations |
SystemUtils | System tool class, copy content to clipboard, pop up and close soft keyboard, clear data, etc |
OtherUtils | RandomUtils Random tool class, SnackUtils, PlatformUtils platform tool class |
MVP | MVP architecture template for the Flutter version, to be improved… |
How does 00.2 use the library
- Specific documents can be demo
01. Event notification Bus class
- Event bus
- The subscriber pattern, which includes the roles of publisher and subscriber, is typically implemented.
- The first way is to implement the bus using the map set to store the key for the event eventName and the value for EventCallback
// Register to listen to bus _subscription = EventBusService.instance.eventBus.on<EventMessage>().listen((event) { String name = event.eventName; // The foreground/background switch has changed if (name == "eventBus1") { var busMessage = event.arguments["busMessage"]; setState(() { message1 = busMessage; }); }});// Send the message EventBusService.instance.eventBus.fire(EventMessage( "eventBus1", arguments: {"busMessage": "Send bus message 1"}));// Page destroy to clear the bus if(_subscription ! =null) { _subscription.cancel(); _subscription = null; } Copy the code
- The second way is to implement bus event notification using StreamController
Bus. on("eventBus2", (arg) {var busMessage = arg; SetState (() {message2 = "receive message:" + busMessage; }); }); Var arg = "send bus message 1"; bus.emit("eventBus2", arg); // Remove message bus.off("eventBus2", (arg) {});Copy the code
02. Color The Color tool class
- Color Color tool class. Convert RGB or ARGB colors to Color objects, hexadecimal Color strings, etc.
HexToColor: convert #FF6325 Color or #50A357D6 Color to hexadecimal Color colorString: ColorString: Checks whether the string is hexadecimalCopy the code
03. Date conversion tool class
- Date conversion tool class. The main methods are to get the current date, format the time in a specified format, and a variety of date formatting tools
GetNowDateTime: Get the current date return DateTime getYesterday: Get the yesterday date return DateTime getNowUtcDateTime: GetNowDateTimeFormat: Gets the current date and returns the specified format. GetUtcDateTimeFormat: Gets the current date and returns the specified format. IsYesterday: GetNowDateString getNowDateString getNowDateString getNowDateString getNowDateString getNowDateString getNowDateString getNowDateString getNowDateString getNowDateString getNowDateString getNowDateString getNowDateString getNowDateString getNowDateString getNowDateString The first field is dateTime, and the second option represents the format formatDateString: FormatDateMilliseconds: for example: '2021-07-18 16:03:10' for example: 'YYYY /M/d HH:mm:ss' for example: Format dateTime milliseconds. The first field is 1213423143312, and the second field is "YYYY /M/d HH:mm:ss". GetWeekday: Obtains dateTime milliseconds. IsToday: indicates whether it isToday based on the timestamp. IsYesterday: indicates whether it was yesterday based on the timeCopy the code
04.File tool class
4.1 File Storage Tool classes
- File storage tool class. This is to store and get String, Json and other files, this is to store to the local file file
GetTempDir: Gets a temporary directory (cache) that the system can clean at any time. GetAppDocDir: Gets the application's directory for storing files that only it can access. The directory is cleared only when the application is deleted. ReadStringDir: Gets data from existing files. By default, it reads to the application directory writeJsonFileDir: WriteStringDir: uses a file to store strings. By default, writeStringDir: writes to an application directory. ClearFileDataDir: deletes cached data. Delete a cache file writeJsonCustomFile: writes a JSON file with a custom path writeStringFile: uses a file to store strings with a custom path readStringCustomFile: Obtains data stored in a file with a custom pathCopy the code
4.2 File management Tools
- File management tool class. The main operation is to create different directory paths, create files, or directory paths.
GetTempPath: Obtains the path of the temporary directory on the device. This directory is not backed up and is suitable for storing the cache of downloaded files. GetAppDocPath: Gets the application's directory for storing files that only it can access. The directory is cleared only when the application is deleted. GetStoragePath: path of the directory where the application can access top-level storage createDirSync: Creates a file asynchronously createDir: creates a file synchronously createTempDir: creates a temporary directory createAppDocDir: creates a temporary directory Create a directory to retrieve the applicationCopy the code
05.Sql database tool class
- To be perfect
06.Json conversion tool class
- Json transformation tool class. Json conversion common operations, gradually improve the list, map and JSON string conversion and so on.
PrintJson: print printJsonEncode: print encodeObj: Convert an object [value] to a Json string getObj: GetObject: Converts A JSON string to an object or JSON map [source] to an object. GetObjList: Converts a JSON string list [source] to an object. GetObjectList: converts a JSON string list [source] to an object. Converts a JSON string or JSON mapping list [source] to an object listCopy the code
07.Log Log printing tool class
- Log Log printing tool class. Five different types of logs. Tag filtering can also be added.
Init: initializes the log, customizes the tag, specifies whether the debug environment is correct, and specifies the maximum length of the log. These fields are optional. D: Prints debug logs. E: Prints error logsCopy the code
08. Screen parameter tool class
- Screen parameter tool class. Get screen width, height, pixel density, status bar, etc. Later perfect adaptation work……
ScreenWidthDp: current device width dp screenHeightDp: current device height DP pixelRatio: current device pixel density screenWidth: ScreenHeight: current device width px = dp * density screenHeight: current device height px = dp * density Bottom safe zone distance DP textScaleFactory: The number of pixels of the font in pixels, the scale of the fontCopy the code
09.Sp lightweight storage tool class
- Sp lightweight storage tool. Sp storage and access to int, String, list, map and other data operations.
HasKey: determines whether data for keys exists putObject: stores data of type object. GetObject: Gets map data for keys in sp. PutObjectList: Storage sp key list collection getObjectList: the set of access to key in the sp list get string: for sp, key string putString: storage sp key string getBool: PutBool: stores the Boolean value of the key in sp. GetInt: Stores the int value of the key in SP. PutInt: Stores the int value of the key in SP. GetDouble: stores the int value of the key in SP. For key in the sp double value putDouble: storage sp double value of the key getStringList: access to key in the sp list < String > value putStringList: PutStringMap: stores list<String> values of keys in sp getStringMap: obtains map values of keys in SP putStringMap: stores map values of keys in SP getDynamic: stores list<String> values of keys in SP GetKeys: Obtains all keys in SP. Remove: removes values of keys in SP. Clear: clears sp. IsInitialized: checks initialization. ForEach: Checks initialization. Iterate over the key and value of the print SPCopy the code
11. Encryption and decryption tool classes
- Encryption and decryption tool classes. Currently, 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 decrypted string xorBase64Encode: XorBase64Decode: XORBase64 decryptionCopy the code
12.Num format processing tool class
- Format processing tool class. It mainly deals with operations related to num format conversion.
IsNum: checks whether the string is an int or a double. GetIntByValueString: converts the numeric string to an int. If the string is not a number, convert to 0. GetDoubleByValueString: Convert a numeric string to a double. GetNumByValueString: converts the numeric string to num with the x decimal place reserved. GetNumByValueDouble: Saves the x decimal place for a floating point number. AddNum: converts the x decimal place for a floating point number. DivideNum: divide two numbers (to prevent precision loss) addDecString: divide two numbers (to prevent precision loss). SubtractDecString: subtracting two numbers (to prevent accuracy loss). MultiplyDecString: multiplying two numbers (to prevent accuracy loss). DivideDecString: dividing two numbers (to prevent accuracy loss).Copy the code
14. Image processing tools
- Other to be improved, add rounded corners, circular cutting pictures, and processing local images and other methods. Later to improve the acquisition of image attributes, image compression, a variety of fillet method.
FileToBase64: Convert file to Base64 networkImageToBase64: fileToBase64: Convert file to Base64 ShowNetImageWh: Load the network image and specify the width and height. Use default preloading loading and error view showNetImageWhError: Load network images and specify width and height. Pass in the error view showNetImageWhPlaceError: Load the network image and specify the width and height. ShowNetImageWhClip: Load the network image and specify the width and height. Cut the rounded corners. ShowNetImageCircle: Load the network image and cut the round imageCopy the code
15. Network processing tools
15.1 Network request tool class
15.2 Url Parsing tool class
- Tool classes for dealing with URL parsing
GetFirstPath: Gets the first parameter in the URL. GetUrlHost: gets the host in the URL. GetUrlScheme: Get url link Scheme getFirstPath: Get the first parameter in the URL. IsURL: Return the regular expression of whether the input matches the URLCopy the code
16. Common regular tool class
- Use regular expressions, borrow from AndroidUtils utility classes, and convert Java to Dart
IsMobileSimple: indicates that the mobile phone number is simple. IsMobileExact: indicates that the mobile phone number is exact. IsTel: indicates that the phone number is accurate. IsIDCard18Exact: indicates the exact id number. 18-digit isEmail: indicates the email address. IsURL: indicates the URL. Verify date verification in YYYY-MM-DD format, with a flat leap year in mind. IsIP: Verify THE IP address. Match: Determine whether the match is regular RegexConstants. RegexConstants.REGEX_BLANK_LINE: blank line RegexConstants.REGEX_QQ_NUM: QQ id RegexConstants.REGEX_CHINA_POSTAL_CODE: Postcode RegexConstants.REGEX_INTEGER: Integer RegexConstants.REGEX_POSITIVE_INTEGER: Positive integer RegexConstants.REGEX_NEGATIVE_INTEGER: Negative integer RegexConstants.REGEX_NOT_NEGATIVE_INTEGER: Non-negative integer RegexConstants.REGEX_NOT_POSITIVE_INTEGER: non-positive integer RegexConstants.REGEX_FLOAT: Floating point RegexConstants.REGEX_POSITIVE_FLOAT: Positive floating point RegexConstants.REGEX_NEGATIVE_FLOAT: Negative floating point RegexConstants.REGEX_NOT_NEGATIVE_FLOAT: non-negative floating point RegexConstants.REGEX_NOT_POSITIVE_FLOAT: non-positive floating pointCopy the code
17.Object Common utility class
- Object related utility classes are as follows:
IsNull: checks whether the object isNull. IsNullOrBlank: checks whether the data is empty or empty (or contains only Spaces). IsEmptyString: checks whether the string is empty. IsEmpty: determines whether object isEmpty. IsNotEmpty: determines whether object isNotEmpty. CompareListIsEqual: compares two sets to see if they are the sameCopy the code
18. Verify related tool classes
- Verify the relevant utility classes
IsNumericOnly: Checks whether the string contains only numbers. IsAlphabetOnly: checks whether the string contains only letters. IsVector: Checks whether the string is a vector file. IsImage: checks whether the string is an image file. IsAudio: checks whether the string is an audio file. IsDocument: Checks whether the string is a doc file. IsExcel: Checks whether the string is an Excel file. IsPPT: Checks whether the string is a PPT file. IsPDF: Checks if the string is a PDF file. IsHTML: Checks if the string is an HTML file. IsURL: Checks if the string is a URL file. IsDateTime: checks whether the string is the email file. IsMD5: checks whether the string isMD5. IsSHA1: checks whether the string isSHA1. Check whether the string for ipv4 isIPv6: check whether the string for ipv6 isPalindrome: check whether the string for palindrome isCaseInsensitiveContains: check whether contain b (lowercase letters as same or explain). IsCaseInsensitiveContainsAny: check whether does it include a, b or b contains a (lowercase letters as the same). IsCamelCase: Checks whether the string value is humped. IsCapitalize: Checks whether the string value is capitalizedCopy the code
19. Route management tools
21.Text The Text utility class
- The text-related tool classes are as follows:
IsEmpty: determine whether the text content isEmpty isNotEmpty: determine whether the text content isNotEmpty startsWith: determine whether the string startsWith xx contains abbreviate: Use the dot abbreviation string compare: compare two strings to see if they are the same hammingDistance: Compare two strings of the same length with different characters. HideNumber: hide the middle n bits of the mobile phone number. For example, hide the mobile phone number 13667225184 as 136****5184 replace: replace the data in the string split: Return the array reverse: reverses the stringCopy the code
22. I18 Extension tool class
- LocatizationExtensionState class: String get String (String id)
- Get content in different Locales channel languages. For example: var name = context.getString(“name”);
- LocatizationExtensionContext class: String get String (String id)
- Get content in different Locales channel languages
- How to add content in different channel languages. In the main function before runApp
AppLocalizations.supportedLocales = [ const Locale('en'.'US'), const Locale('pt'.'BR'), const Locale('ja'.'JP'), const Locale('zh'.'CN')];Copy the code
23.Time Tool class
24.SPI help tool class
- A Brief introduction to SPI
- Service Locator separates and decouples the interface (abstract base class) from the concrete implementation, while allowing access to the concrete implementation from any location in the App through the interface.
// Register GetIt serviceLocator = GetIt. Instance; getIt.registerSingleton<BusinessService>(new BusinessServiceImpl()); BusinessService = serviceLocator<BusinessService>(); businessService.noneBusinessPattern(); / / the third solution to tie the serviceLocator. ResetLazySingleton < BusinessService > ();Copy the code
25. Timer helper class
- Timer helper class
TimerUtils: set the countdown Timer setTotalTime: Set the total countdown time setInterval: set the Timer interval startTimer: start the Timer Timer updateTotalTime: Reset the total countdown time isActive: determines whether the Timer is started. PauseTimer: Suspends the countdown Timer. Cancel: cancels the countdown TimerCopy the code
26. Common extension tool classes
Int extension class: ExtensionInt
- ExtensionInt expanding class
IsOneAKind: Check whether all the data has the same value. ToBinaryInt: Check whether the int is a palindrome. Converts an int value to a binary stringCopy the code
26.2 List Extension: ExtensionList
- ExtensionList expanding class
ToJsonString: converts list toJsonString getJsonPretty: converts list toJsonString, newline valueTotal: gets total value of num list (int/double) isNull: IsNullOrBlank: Checks whether the data is empty or empty (empty or contains only Spaces)Copy the code
26.3 Map Extension class: ExtensionMap
- ExtensionMap extension class
ToJsonString: converts a map to a JSON string. GetJsonPretty: converts a map to a JSON string. Newline.Copy the code
26.4 String Extension class: ExtensionString
- ExtensionString expanding class
IsNull: checks whether the object isNull. IsNullOrBlank: checks whether the data is empty or empty (empty or contains only Spaces). IsNumericOnly: checks whether the string contains only numbers. IsVector: Checks whether the string is a vector file. IsImage: checks whether the string is an image file. IsAudio: checks whether the string is an audio file. IsDocument: Checks whether the string is a doc file. IsExcel: Checks whether the string is an Excel file. IsPPT: Checks whether the string is a PPT file. IsPDF: Checks if the string is a PDF file. IsHTML: Checks if the string is an HTML file. IsURL: Checks if the string is a URL file. IsDateTime: checks whether the string is the email file. IsMD5: checks whether the string isMD5. IsSHA1: checks whether the string isSHA1. Check whether the string for ipv4 isIPv6: check whether the string for ipv6 isPalindrome: check whether the string for palindrome isCaseInsensitiveContains: check whether contain b (lowercase letters as same or explain). IsCaseInsensitiveContainsAny: check whether does it include a, b or b contains a (lowercase letters as the same). IsCamelCase: Checks whether the string value is humped. IsCapitalize: Checks whether the string value is capitalizedCopy the code
33. Transform related tool classes
- Transform the related operation tool classes
You can use toBinaryInt to transform an int into a binary and capitalize the capitalize that you bring to the book CapitalizeFirst: Capitalize the first letter of the string and the other letters in lowercase removeAllWhitespace: remove all Spaces in the string. NumericOnly: Extract the numeric value of the stringCopy the code
34. Global exception catching tool
- For flutter global exception capture, use: handLE_Exception
// If used, in the main method, look like this: hookCrash(() {runApp(MainApp()); });Copy the code
- To 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---->Copy the code
35. Parse data utility class
- Parse XML/HTML data utility class
36. Byte conversion tool class
- ByteUtils transforms the related operation tool class
ToBinary: convert the int toBinary toReadable: convert the byte array to a readable string toBase64: convert the byte array to a base64 string fromBase64: convert the base64 string to a byte array clone: Clone byte array same: determine whether two bytes are identical Extract: extract data from a sequence of bytes Combine: combine two bytes insert: insert a byte into an index of a byte remove: remove a byte from an index of a byteCopy the code
40. Other related tool classes
40.2 Random tool class
- RandomUtils
RandomColor: generates a random integer representing a hexadecimal color randomString: generates a randomString of a specified length or random length randInt: generates a random number between the beginning and the end randomElement: returns a randomElement from a listCopy the code
40.3 Obtaining platform tools
- PlatformUtils. The utility class can differentiate platform information by taking the platform and then 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 an Android device, value is: AndroidCopy the code
Clipboard tool class
- System tools, mainly soft keyboard operations and copy content to the clipboard
CopyToClipboard: copies the text to the clipboard. HideKeyboard: hides the soft keyboard. For details, see the following: TextInputChannel showKeyboard: displays the soft keyboardCopy the code
41. Reference items and blogs
- Github.com/Blankj/Andr…
- Pub. Dev/packages/em…
- Blog.csdn.net/iotjin/arti…
- Cloud.tencent.com/developer/a…
- Blog.csdn.net/yechaoa/art…
- Blog.csdn.net/aau88497/ar…
- Github.com/Sky24n/flus…
- Github.com/a14n/dart-d…
- Pub. Dev/packages? Q =…