The Flutter utility libraryflustars
SpUtil: singleton “synchronize “SharedPreferences utility class ScreenUtil: WidgetUtil: Widget class DirectoryUtil: ScreenUtil: Widget class DirectoryUtil: file directory class DioUtil: Singleton Dio networking utility class.
Dart common utility class library Common_utils
TimelineUtil: time axis. TimerUtil: countdown, timed task. MoneyUtil: accurate conversion, metaconvert, metaconvert, support format output. RegexUtil: RegexUtil: RegexUtil: RegexUtil: RegexUtil: RegexUtil: RegexUtil: RegexUtil: RegexUtil: RegexUtil: RegexUtil: RegexUtil: RegexUtil: RegexUtil: RegexUtil: RegexUtil: RegexUtil: RegexUtil: RegexUtil: RegexUtil: RegexUtil: RegexUtil: RegexUtil EnDecodeUtil: EnDecodeUtil: md5 encryption, Base64 encryption/decryption TextUtil: bank card number with Spaces every 4 bits, comma every 3 bits, hidden mobile phone number, etc.
SpUtil
Singleton “synchronize “SharedPreferences utility class. Support get pass default value, support store object, support store object array. Because SharedPreferences need to be generated asynchronously to use. Method 1: Run the APP after Sp is generated. Example Project 1 Method 2: Add a Splash page. After the splash page is initialized, you can access the home page to use the page synchronously. Example Project 2
A / / / way
// wait for sp initialization to complete before running app.
/// Sp initialization time is around 30ms in release mode and over 100ms in debug mode.
void main() async {
await SpUtil.getInstance();
runApp(MyApp());
}
class MyAppState extends State<MyApp> {
@override
void initState() {
super.initState();
// use Sp synchronously.
SpUtil.remove("username");
String defName = SpUtil.getString("username", defValue: "sky");
SpUtil.putString("username"."sky24");
String name = SpUtil.getString("username");
print("MyApp defName: $defName, name: $name");
}
@override
Widget build(BuildContext context) {
returnMaterialApp(); }}// App starts to read Sp data and waits asynchronously for Sp initialization to complete.
await SpUtil.getInstance();
// A general access example.
// Default values are supported. String bool int double StringList.
SpUtil.putString("username"."sky24");
String defName = SpUtil.getString("username");
String defName = SpUtil.getString("username", defValue: "sky");
// An example of accessing entity objects.
City city = new City();
city.name = "Chengdu";
// Store entity objects.
SpUtil.putObject("loc_city", city);
// Read entity objects.
City hisCity = SpUtil.getObj("loc_city", (v) => City.fromJson(v));
// Access entity object list example.
List<City> list = new List(a); list.add(new City(name: "Chengdu"));
list.add(new City(name: "Beijing"));
// Store the entity object list.
SpUtil.putObjectList("loc_city_list", list);
// Read the entity object list.
List<City> dataList = SpUtil.getObjList("loc_city_list", (v) => City.fromJson(v));
Copy the code
ScreenUtil
Screen adaptation, compatible with horizontal/vertical screen switching adaptation, get screen width, height, density, AppBar height, status bar height, screen orientation.
One, do not rely on context/ / the screen width
double screenWidth = ScreenUtil.getInstance().screenWidth;
/ / screen
double screenHeight = ScreenUtil.getInstance().screenHeight;
// Screen pixel density
double screenDensity = ScreenUtil.getInstance().screenDensity;
// System status bar height
double statusBarHeight = ScreenUtil.getInstance().statusBarHeight;
/ / BottomBar height
double bottomBarHeight = ScreenUtil.getInstance().bottomBarHeight;
// System AppBar height
double appBarHeight = ScreenUtil.getInstance().appBarHeight;
// Get the fit size
double adapterSize = ScreenUtil.getInstance().getAdapterSize(100); 2. Rely on context/ / the screen width
double screenWidth = ScreenUtil.getScreenW(context);
/ / screen
double screenHeight = ScreenUtil.getScreenH(context);
// Screen pixel density
double screenDensity = ScreenUtil.getScreenDensity(context);
// System status bar height
double statusBarHeight = ScreenUtil.getStatusBarH(context);
/ / BottomBar height
double bottomBarHeight = ScreenUtil.getBottomBarH(context);
// Screen orientation
Orientation orientation = ScreenUtil.getOrientation(context);
// Get the fit size
double adapterSize = ScreenUtil.getAdapterSizeCtx(context, 100);
Copy the code
WidgetUtil
Listen for Widget rendering status, get Widget width, height, on-screen coordinates, and network/local image size.
AsyncPrepare: Widget renders a listener that listens to the Widget's width and height, and callback returns the width and height parameters. GetImageWHE: Gets the width and height of the image, returns rect.zero in px for loading errors. GetImageWHE: Gets the width and height of the image, raises an exception for loading errors./// Widget render listener.
WidgetUtil widgetUtil = new WidgetUtil();
widgetUtil.asyncPrepare(context, true, (Rect rect) {
// Widget rendering complete.
});
/// Width of the widget.
Rect rect = WidgetUtil.getWidgetBounds(context);
/// Coordinates of the widget on the screen.
Offset offset = WidgetUtil.getWidgetLocalToGlobal(context);
// get the image size under CachedNetworkImage
Image image = new Image(image: new CachedNetworkImageProvider("Url"));
Rect rect1 = await WidgetUtil.getImageWH(image: image);
/ / / the other image
Image imageAsset = new Image.asset("");
Image imageFile = new Image.file(File("path"));
Image imageNetwork = new Image.network("url");
Image imageMemory = new Image.memory(null);
/// get the network image size
Rect rect2 = await WidgetUtil.getImageWH(url: "Url");
/// Obtain the local image size localUrl requires the full path
Rect rect3 = await WidgetUtil.getImageWH(localUrl: "Assets/images / 3.0 x/ali_connors. PNG");
/// Other ways
WidgetUtil.getImageWH(url: "Url").then((Rect rect) {
print("rect: " + rect.toString();
});
WidgetUtil.getImageWHE(url: "Url").then((Rect rect) {
print("rect: " + rect.toString();
}).catchError((error) {
print("rect: " + error.toString();
});
Copy the code
DirectoryUtil
File directory utility class.
await DirectoryUtil.getInstance();
String path = DirectoryUtil.getTempPath(fileName: 'demo.png', category: 'image');
String path = DirectoryUtil.getAppDocPath(fileName: 'demo.mp4', category: 'video');
String path = DirectoryUtil.getStoragePath(fileName: 'flutterwanandroid.apk', package: 'com.thl.flutterwanandroid');
Directory dir = DirectoryUtil.createTempDirSync(package: 'doc', category: 'image');
Copy the code
DioUtil
Singleton DioUtil, migrated to this location DioUtil. (Based on V1.0.13, for reference only ~)
// Enable debug mode.
DioUtil.openDebug();
// Set network parameters.
Options options = DioUtil.getDefOptions();
options.baseUrl = "http://www.wanandroid.com/";
HttpConfig config = new HttpConfig(options: options);
DioUtil().setConfig(config);
// Two singleton request modes.
DioUtil().request<List>(Method.get."banner/json");
DioUtil.getInstance().request(Method.get."banner/json");
/ / sample
LoginReq req = new LoginReq('username'.'password');
DioUtil().request(Method.post, "user/login",data: req.toJson());
/ / sample
FormData formData = new FormData.from({
"username": "username"."password": "password"}); DioUtil().requestR(Method.post,"user/login",data: rformData);
Copy the code
TextUtil
Replace (new) replace (new) replace (new) replace (new) replace (new) replace (new) replace (new) replace (new) replace (new) Replace.(new) split: split.(new) // example String phoneNo = textutil.formatspace4 ("15845678910"); // 1584 5678 910
String num = TextUtil.formatComma3("1234"); // 123,4 String phoneNo = textutil.hidephone ("15845678910") / / 158 * * * * 8910Copy the code
EnDecodeUtil
EncodeMd5: MD5 encryption (new) encodeBase64: Base64 encryption (new) decodeBase64() : Base64 decryptionCopy the code
TimelineUtil
The timeline. For example: wechat moments, Weibo timeline, Alipay timeline.
///(xx) is configurable output
enum DayFormat {
//(less than 10s-> just), x minutes, x hours, (yesterday), x days.
Simple,
Just 10 s - > / / / (less than), x, x hours, [this year: () / 1 day before yesterday, (2 days ago), the MM - dd], [past: yyyy - MM - dd).
Common,
/// < 10s-> just), x minutes, x hours,[this year: (yesterday :mm/1 day ago), (2 days ago), MM-DD HH:mm],[previous year: YYYY-MM-DD HH:mm].
Full,
}
/// Configure the Timeline information.
abstract class TimelineInfo {
String suffixAgo(); //suffix ago(suffix)
String suffixAfter(); //suffix after(suffix)
String lessThanTenSecond() => ' '; // Just now.
String customYesterday() => ' '; //Yesterday. Priority is higher than keepOneDay
bool keepOneDay(); Example: true -> 1 day ago, false -> MM-dd.
bool keepTwoDays(); Example: true -> 2 days ago, false -> MM-dd.
String oneMinute(int minutes); //a minute(1 minute).
String minutes(int minutes); // Take x minutes.
String anHour(int hours); // An hour is an hour.
String hours(int hours); // X hours(x hours)
String oneDay(int days); / / a day (1 day).
String days(int days); / / x days (x days).
DayFormat dayFormat(); //format.} setLocaleInfo: custom configuration information formatByDateTime: format the output timeline information byDateTimeFormat: Displays the timeline information in format.Copy the code
TimerUtil
Countdown, timed task.
SetInterval: set Timer interval setTotalTime: set total countdown time startTimer() : startTimer. Start Timer Timer. UpdateTotalTime: reset the total time of the countdown. Cancel: cancel the Timer. SetOnTimerTickCallback: Timer callback. IsActive: Whether the Timer is started. TimerUtil timerUtil;// Scheduled task test
timerUtil = new TimerUtil(mInterval: 1000);
//timerUtil.setInterval(1000);
timerUtil.setOnTimerTickCallback((int value) {
LogUtil.e("TimerTick: " + value.toString());
});
timerUtil.startTimer();
if(timerUtil ! =null) timerUtil.cancel(); //dispose()
TimerUtil timerCountDown;
// Countdown test
timerCountDown = new TimerUtil(mInterval: 1000, mTotalTime: 3 * 1000);
// timerCountDown.setInterval(1000);
// timerCountDown.setTotalTime(3 * 1000);
timerCountDown.setOnTimerTickCallback((int value) {
double tick = (value / 1000);
LogUtil.e("CountDown: " + tick.toInt().toString());
});
timerCountDown.startCountDown();
if(timerCountDown ! =null) timerCountDown.cancel(); //dispose()
Copy the code
MoneyUtil
Amount tool class, minute/yuan mutual conversion, accurate conversion, prevent precision loss.
ChangeF2Y: converted into a character string, output in format changeFStr2YWithUnit Format and unit Format Output changeYWithUnit: format and unit format output changeY2F: format and unit outputCopy the code
LogUtil
Simple package printing log, complete output of long log.
Init (isDebug, tag) : isDebug: mode, tag e(Object, tag) : log e V (object, tag) : log V, output only in debug mode.Copy the code
DateUtil
Date utility class, pay for custom format output.
enum DateFormat {
DEFAULT, //yyyy-MM-dd HH:mm:ss.SSS
NORMAL, //yyyy-MM-dd HH:mm:ss
YEAR_MONTH_DAY_HOUR_MINUTE, //yyyy-MM-dd HH:mm
YEAR_MONTH_DAY, //yyyy-MM-dd
YEAR_MONTH, //yyyy-MM
MONTH_DAY, //MM-dd
MONTH_DAY_HOUR_MINUTE, //MM-dd HH:mm
HOUR_MINUTE_SECOND, //HH:mm:ss
HOUR_MINUTE, //HH:mm
ZH_DEFAULT, // YYYY year MM month DD day HH hour MM minute ss second SSS ms
ZH_NORMAL, TimeSeparate :" :" --> YYYY yyyy HH: MM :ss
ZH_YEAR_MONTH_DAY_HOUR_MINUTE, TimeSeparate :" :" --> YYYy-yyyy HH: MM
ZH_YEAR_MONTH_DAY, // YYYY MM month DD date
ZH_YEAR_MONTH, From MM/yyyy
ZH_MONTH_DAY, On the dd/MM
ZH_MONTH_DAY_HOUR_MINUTE, / / MMDd day HH mm/timeSeparate:":"HH: MM ZH_HOUR_MINUTE_SECOND,//HH mm minute ss second
ZH_HOUR_MINUTE, / / HH mm points} formatDate: formatDateDateTime(new) formatDateStr: format date string (new) formatDateMs: format date millisecond (new) getNowDateMs: Get the current millisecond getNowDateStr: (YYYY-MM-DD HH: MM :ss) getDateMsByTimeStr: get milliseconds By date string (Format output). GetDateStrByTimeStr: GetDateStrByMs: Gets the date string By ms (Format output). GetDateStrByDateTime: Gets the date string ByDateTime(Format output). GetWeekDay: Obtains WeekDay ByDateTime.getZhweekday: Gets the week ByDateTimeGetWeekDayByMs: Obtain WeekDayBy ms getZHWeekDayByMs: obtain week By ms isLeapYearByYear: Whether it is a leap year yearIsEqual: IsYesterday: whether it isYesterday. IsToday: whether it isToday. IsWeek: whether it is this week./// DateUtil
DateUtil.formatDateMs(DateTime.now().millisecondsSinceEpoch, format: DataFormats.full); / / the 2019-07-09 16:51:14
DateUtil.formatDateStr("The 2019-07-09 16:51:14", format: "yyyy/M/d HH:mm:ss"); / / 2019/7/9 16:51:14
DateUtil.formatDate(DateTime.now(), format: "yyyy/MM/dd HH:mm:ss"); / / 2019/07/09 16:51:14
Copy the code
RegexUtil
Regular utility classes.
IsMobileSimple: mobile phone number isMobileExact: mobile phone number isTel: phone number isIDCard: ID number isIDCard15: ID number15Bit isIDCard18: simply verify the id card number18Bit isIDCard18Exact: indicates the exact id card number18Bit isEmail: verify mailbox isURL: verify URL isZh: verify Chinese characters isDate: verify date verification in YYYY-MM-DD format with even leap year taken into account isIP: verify IP addressCopy the code
NumUtil
Numerical operation tool class, retain x decimal, accurate addition, subtraction, multiplication, division, to prevent precision loss.
GetIntByValueStr: digit string transferint. GetDoubleByValueStr: number string transferdoubleGetNumByValueStr: reserve x decimal by Number string getNumByValueDouble: reserve X decimal bydoubleWe are setting up a special sum.add (precise addition to prevent loss of precision).subtract (precise multiplication).divide (precise division).subtract (precise deduction).subtract (precise deduction).subtract (precise deduction).divide (precise deduction)Copy the code
ObjectUtil
Check whether the object is empty (String List Map). Check whether two lists are equal.
Judge isEmptyString:StringIsEmptyList: Indicates whether the value is emptyListIsEmptyMap: Determines whether the value is emptyMapIsEmpty: checks whether the object isEmpty.String List MapIsNotEmpty: determines whether an object isNotEmpty.String List Map).twolistisequal: Judge twoListIs it equal?Copy the code
About the author
GitHub: Sky24n Brief book: Sky24n Nuggets: Sky24n Pub: Sky24n
Project example
GitHub: Flutter_demos APK: Click download v0.2.1 Android scan code download APK:
Screenshot