全網最全Flutter經常使用工具類

Flutter工具類庫 flustars

一、SpUtil : 單例"同步"SharedPreferences工具類。
二、ScreenUtil : 屏幕工具類.
三、WidgetUtil : Widget具類.
四、DirectoryUtil : 文件目錄工具類。
五、DioUtil : 單例Dio網絡工具類。android

Dart經常使用工具類庫common_utilsgit

一、TimelineUtil : 時間軸.
二、TimerUtil : 倒計時,定時任務.
三、MoneyUtil : 精確轉換,元轉分,分轉元,支持格式輸出.
四、LogUtil : 簡單封裝打印日誌.
五、DateUtil : 日期轉換格式化輸出.
六、RegexUtil : 正則驗證手機號,身份證,郵箱等等.
七、NumUtil : 保留x位小數, 精確加、減、乘、除, 防止精度丟失.
八、ObjectUtil : 判斷對象是否爲空(String List Map),判斷兩個List是否相等.
九、EnDecodeUtil : md5加密,Base64加/解密.
十、TextUtil : 銀行卡號每隔4位加空格,每隔3三位加逗號,隱藏手機號等等.github

SpUtil

單例"同步"SharedPreferences工具類。支持get傳入默認值,支持存儲對象,支持存儲對象數組。因爲SharedPreferences須要異步生成才能使用。
方式一:簡單粗暴,等待Sp生成後再運行app。示例項目一
方式二:增長splash頁面,在splash頁面完初始化,進入主頁就能夠同步使用。示例項目二json

/// 方式一
/// 等待sp初始化完成後再運行app。
/// sp初始化時間 release模式下30ms左右,debug模式下100多ms。
void main() async {
  await SpUtil.getInstance();
  runApp(MyApp());
}

class MyAppState extends State<MyApp> {
  @override
  void initState() {
    super.initState();
    /// 同步使用Sp。
    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) {
    return MaterialApp();
  }
} 

// App啓動時讀取Sp數據,須要異步等待Sp初始化完成。
await SpUtil.getInstance();

// 常規存取示例。
//支持默認值。String,bool,int,double,StringList。
SpUtil.putString("username", "sky24");
String defName = SpUtil.getString("username");
String defName = SpUtil.getString("username", defValue: "sky");

// 存取實體對象示例。
City city = new City();
city.name = "成都市";
// 存儲實體對象。
SpUtil.putObject("loc_city", city);
// 讀取實體對象。
City hisCity = SpUtil.getObj("loc_city", (v) => City.fromJson(v)); 

// 存取實體對象list示例。
List<City> list = new List();
list.add(new City(name: "成都市"));
list.add(new City(name: "北京市"));
// 存儲實體對象list。
SpUtil.putObjectList("loc_city_list", list);
// 讀取實體對象list。
List<City> dataList = SpUtil.getObjList("loc_city_list", (v) => City.fromJson(v)); 
複製代碼

ScreenUtil

屏幕適配,兼容橫/縱屏切換適配,獲取屏幕寬、高、密度,AppBar高,狀態欄高度,屏幕方向.數組

1、不依賴context
// 屏幕寬
double screenWidth = ScreenUtil.getInstance().screenWidth;
// 屏幕高
double screenHeight = ScreenUtil.getInstance().screenHeight;
// 屏幕像素密度
double screenDensity = ScreenUtil.getInstance().screenDensity;
// 系統狀態欄高度
double statusBarHeight = ScreenUtil.getInstance().statusBarHeight;
// BottomBar高度 
double bottomBarHeight = ScreenUtil.getInstance().bottomBarHeight;
// 系統AppBar高度
double appBarHeight = ScreenUtil.getInstance().appBarHeight;
// 獲取適配後的尺寸
double adapterSize = ScreenUtil.getInstance().getAdapterSize(100);

2、依賴context
// 屏幕寬
double screenWidth = ScreenUtil.getScreenW(context);
// 屏幕高
double screenHeight = ScreenUtil.getScreenH(context);
// 屏幕像素密度
double screenDensity = ScreenUtil.getScreenDensity(context);
// 系統狀態欄高度
double statusBarHeight = ScreenUtil.getStatusBarH(context);
// BottomBar高度
double bottomBarHeight = ScreenUtil.getBottomBarH(context);
// 屏幕方向
Orientation orientation = ScreenUtil.getOrientation(context);
// 獲取適配後的尺寸
double adapterSize = ScreenUtil.getAdapterSizeCtx(context, 100);
複製代碼

WidgetUtil

監聽Widget渲染狀態,獲取Widget寬高,在屏幕上的座標,獲取網絡/本地圖片尺寸.bash

asyncPrepare              : Widget渲染監聽,監聽widget寬高變化,callback返回寬高等參數.
getWidgetBounds           : 獲取widget 寬高.
getWidgetLocalToGlobal    : 獲取widget在屏幕上的座標.
getImageWH                : 獲取圖片寬高,加載錯誤狀況返回 Rect.zero.(單位 px). 
getImageWHE               : 獲取圖片寬高,加載錯誤會拋出異常.(單位 px). 

/// widget渲染監聽。
WidgetUtil widgetUtil = new WidgetUtil();
widgetUtil.asyncPrepare(context, true, (Rect rect) {
  // widget渲染完成。
});

/// widget寬高。
Rect rect = WidgetUtil.getWidgetBounds(context);

/// widget在屏幕上的座標。
Offset offset = WidgetUtil.getWidgetLocalToGlobal(context);
  
/// 獲取CachedNetworkImage下的圖片尺寸
Image image = new Image(image: new CachedNetworkImageProvider("Url"));
Rect rect1 = await WidgetUtil.getImageWH(image: image);  

/// 其餘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);

/// 獲取網絡圖片尺寸
Rect rect2 = await WidgetUtil.getImageWH(url: "Url");

/// 獲取本地圖片尺寸 localUrl 須要全路徑
Rect rect3 = await WidgetUtil.getImageWH(localUrl: "assets/images/3.0x/ali_connors.png");

/// 其餘方式
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();
});
複製代碼

DirectoryUtil

文件目錄工具類.微信

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');
複製代碼

DioUtil

單例DioUtil,已遷移至此處DioUtil。(基於v1.0.13,僅供參考~)markdown

// 打開debug模式.
DioUtil.openDebug();   
  
// 配置網絡參數.
Options options = DioUtil.getDefOptions();
options.baseUrl = "http://www.wanandroid.com/";
HttpConfig config = new HttpConfig(options: options);
DioUtil().setConfig(config);
  
// 兩種單例請求方式.
DioUtil().request<List>(Method.get, "banner/json");
DioUtil.getInstance().request(Method.get, "banner/json");
  
//示例
LoginReq req = new LoginReq('username', 'password');
DioUtil().request(Method.post, "user/login",data: req.toJson());
  
//示例
FormData formData = new FormData.from({
      "username": "username",
      "password": "password",
    });
DioUtil().requestR(Method.post, "user/login",data: rformData);
複製代碼

TextUtil

isEmpty                     : isEmpty.(新)
formatSpace4                : 每隔4位加空格,格式化銀行卡.(新)
formatComma3                : 每隔3三位加逗號.(新)
hidePhone                   : 隱藏手機號.(新)
replace                     : replace.(新)
split                       : split.(新)
  
/// example
String phoneNo = TextUtil.formatSpace4("15845678910"); // 1584 5678 910
String num     = TextUtil.formatComma3("1234"); // 123,4
String phoneNo = TextUtil.hidePhone("15845678910")// 158****8910
複製代碼

EnDecodeUtil

encodeMd5                   : md5 加密.(新)
encodeBase64                : Base64加密.(新)
decodeBase64()              : Base64解密.(新)
複製代碼

TimelineUtil

時間軸。例如:微信朋友圈,微博時間軸,支付寶時間軸。網絡

///(xx)爲可配置輸出
enum DayFormat {
  ///(小於10s->剛剛)、x分鐘、x小時、(昨天)、x天.
  Simple,
  ///(小於10s->剛剛)、x分鐘、x小時、[今年: (昨天/1天前)、(2天前)、MM-dd],[往年: yyyy-MM-dd].
  Common,
  ///小於10s->剛剛)、x分鐘、x小時、[今年: (昨天 HH:mm/1天前)、(2天前)、MM-dd HH:mm],[往年: yyyy-MM-dd HH:mm].
  Full,
}
///Timeline信息配置.
abstract class TimelineInfo {
  String suffixAgo(); //suffix ago(後綴 後).
  String suffixAfter(); //suffix after(後綴 前).
  String lessThanTenSecond() => ''; //just now(剛剛).
  String customYesterday() => ''; //Yesterday(昨天).優先級高於keepOneDay
  bool keepOneDay(); //保持1天,example: true -> 1天前, false -> MM-dd.
  bool keepTwoDays(); //保持2天,example: true -> 2天前, false -> MM-dd.
  String oneMinute(int minutes); //a minute(1分鐘).
  String minutes(int minutes); //x minutes(x分鐘).
  String anHour(int hours); //an hour(1小時).
  String hours(int hours); //x hours(x小時).
  String oneDay(int days); //a day(1天).
  String days(int days); //x days(x天).
  DayFormat dayFormat(); //format.
}
setLocaleInfo               : 自定義設置配置信息.
formatByDateTime            : 格式輸出時間軸信息 by DateTime .
format                      : 格式輸出時間軸信息.
複製代碼

TimerUtil

倒計時,定時任務。app

setInterval                 : 設置Timer間隔.
setTotalTime                : 設置倒計時總時間.
startTimer()                : 啓動定時Timer.
startCountDown              : 啓動倒計時Timer.
updateTotalTime             : 重設倒計時總時間.
cancel                      : 取消計時器.
setOnTimerTickCallback      : 計時器回調.
isActive                    : Timer是否啓動.

  TimerUtil timerUtil;
  //定時任務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;
  //倒計時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()

複製代碼

MoneyUtil

金額工具類,分/元互轉,精確轉換,防止精度丟失。

changeF2Y                   : 分 轉 元, format格式輸出.
changeFStr2YWithUnit        : 分字符串 轉 元, format 與 unit 格式 輸出.
changeF2YWithUnit           : 分 轉 元, format 與 unit 格式 輸出.
changeYWithUnit             : 元, format 與 unit 格式 輸出.
changeY2F                   : 元 轉 分.
複製代碼

LogUtil

簡單封裝打印日誌,可完整輸出超長log。

init(isDebug, tag)          : isDebug: 模式, tag 標籤.
e(object, tag)              : 日誌e
v(object, tag)              : 日誌v,只在debug模式輸出.
複製代碼

DateUtil

日期工具類,支付自定義格式輸出。

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年MM月dd日 HH時mm分ss秒SSS毫秒
  ZH_NORMAL, //yyyy年MM月dd日 HH時mm分ss秒 / timeSeparate: ":" --> yyyy年MM月dd日 HH:mm:ss
  ZH_YEAR_MONTH_DAY_HOUR_MINUTE, //yyyy年MM月dd日 HH時mm分 / timeSeparate: ":" --> yyyy年MM月dd日 HH:mm
  ZH_YEAR_MONTH_DAY, //yyyy年MM月dd日
  ZH_YEAR_MONTH, //yyyy年MM月
  ZH_MONTH_DAY, //MM月dd日
  ZH_MONTH_DAY_HOUR_MINUTE, //MM月
  dd日 HH時mm分  /  timeSeparate: ":" --> MM月dd日 HH:mm
  ZH_HOUR_MINUTE_SECOND, //HH時mm分ss秒
  ZH_HOUR_MINUTE, //HH時mm分
}
formatDate                      : 格式化日期 DateTime.(新)
formatDateStr                   : 格式化日期 字符串.(新)
formatDateMs                    : 格式化日期 毫秒.(新)
getNowDateMs                    : 獲取如今 毫秒.
getNowDateStr                   : 獲取如今 日期字符串.(yyyy-MM-dd HH:mm:ss)
getDateMsByTimeStr              : 獲取毫秒 By 日期字符串(Format格式輸出).
getDateStrByTimeStr             : 獲取日期字符串 By 日期字符串(Format格式輸出).
getDateStrByMs                  : 獲取日期字符串 By 毫秒(Format格式輸出).
getDateStrByDateTime            : 獲取日期字符串 By DateTime(Format格式輸出).
getWeekDay                      : 獲取WeekDay By DateTime.
getZHWeekDay                    : 獲取星期 By DateTime.
getWeekDayByMs                  : 獲取WeekDay By 毫秒.
getZHWeekDayByMs                : 獲取星期 By 毫秒.
isLeapYearByYear                : 是不是閏年.
yearIsEqual                     : 是否同年.
getDayOfYear                    : 在今年的第幾天.
isYesterday                     : 是不是昨天.
isToday                         : 是不是今天.
isWeek                          : 是不是本週.(新)

/// DateUtil
DateUtil.formatDateMs(DateTime.now().millisecondsSinceEpoch, format: DataFormats.full); // 2019-07-09 16:51:14
DateUtil.formatDateStr("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
複製代碼

RegexUtil

正則工具類。

isMobileSimple            : 簡單驗證手機號
isMobileExact             : 精確驗證手機號
isTel                     : 驗證電話號碼
isIDCard                  : 驗證身份證號碼
isIDCard15                : 驗證身份證號碼 15 位
isIDCard18                : 簡單驗證身份證號碼 18 位
isIDCard18Exact           : 精確驗證身份證號碼 18 位
isEmail                   : 驗證郵箱
isURL                     : 驗證 URL
isZh                      : 驗證漢字
isDate                    : 驗證 yyyy-MM-dd 格式的日期校驗,已考慮平閏年
isIP                      : 驗證 IP 地址
複製代碼

NumUtil

數值運算工具類,保留x位小數, 精確加、減、乘、除, 防止精度丟失.

getIntByValueStr            : 數字字符串轉int.
getDoubleByValueStr         : 數字字符串轉double.
getNumByValueStr            : 保留x位小數 by 數字字符串.
getNumByValueDouble         : 保留x位小數 by double.
add                         : 加(精確相加,防止精度丟失).
subtract                    : 減(精確相減,防止精度丟失).
multiply                    : 乘(精確相乘,防止精度丟失).
divide                      : 除(精確相除,防止精度丟失).
複製代碼

ObjectUtil

判斷對象是否爲空(String List Map),判斷兩個List是否相等.

isEmptyString             : 判斷String是否爲空.
isEmptyList               : 判斷List是否爲空.
isEmptyMap                : 判斷Map是否爲空.
isEmpty                   : 判斷對象是否爲空.(String List Map).
isNotEmpty                : 判斷對象是否非空.(String List Map).
twoListIsEqual            : 判斷兩個List是否相等.
複製代碼

關於做者

GitHub : Sky24n
簡書     : Sky24n
掘金     : Sky24n
Pub      : Sky24n

項目示例

GitHub : flutter_demos
APK      :點擊下載 v0.2.1
Android掃碼下載APK:

flutter_wanandroid

Screenshot

相關文章
相關標籤/搜索