file_path stringlengths 3 280 | file_language stringclasses 66 values | content stringlengths 1 1.04M | repo_name stringlengths 5 92 | repo_stars int64 0 154k | repo_description stringlengths 0 402 | repo_primary_language stringclasses 108 values | developer_username stringlengths 1 25 | developer_name stringlengths 0 30 | developer_company stringlengths 0 82 |
|---|---|---|---|---|---|---|---|---|---|
example/lib/utils/log_utils_page.dart | Dart | import 'package:flutter/material.dart';
import 'package:yc_flutter_utils/log/log_utils.dart';
class LogUtilsPage extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return new LogUtilsState();
}
}
class LogUtilsState extends State<LogUtilsPage>{
@override
void initState() {
super.initState();
}
@override
void dispose() {
super.dispose();
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(title: new Text("测试LogUtils工具类的功能")),
body: ListView(
children: <Widget>[
new Text("测试LogUtils工具类的功能"),
RaisedButton(
onPressed: () {
LogUtils.d("---------onPressed-",tag: "xiaoyang");
},
color: const Color(0xffff0000),
child: new Text('打印d日志'),
),
new Divider(),
RaisedButton(
onPressed: () {
LogUtils.e("---------onPressed-",tag: "yangchong");
},
color: const Color(0xffff0000),
child: new Text('打印e日志,并带有tag'),
),
new Divider(),
RaisedButton(
onPressed: () {
LogUtils.i("---------onPressed-",tag: "yangchong");
},
color: const Color(0xffff0000),
child: new Text('打印i日志,并带有tag'),
),
],
));
}
}
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
example/lib/utils/num_utils_page.dart | Dart |
import 'package:flutter/material.dart';
import 'package:yc_flutter_utils/date/data_formats.dart';
import 'package:yc_flutter_utils/date/date_utils.dart';
import 'package:yc_flutter_utils/num/num_utils.dart';
class NumPage extends StatefulWidget {
NumPage();
@override
State<StatefulWidget> createState() {
return new _DatePageState();
}
}
class _DatePageState extends State<NumPage> {
String str1 = "124321423";
String str2 = "1243.21423";
double d = 12312.3121;
double d2 = 12312.3121;
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
DateTime dateTime = new DateTime.now();
return Scaffold(
appBar: new AppBar(
title: new Text("DateUtils工具类"),
centerTitle: true,
),
body: new Column(
children: <Widget>[
new Text("将数字字符串转int:" + NumUtils.getIntByValueString(str1).toString()),
new Text("将数字字符串转int:" + NumUtils.getIntByValueString("yangchong").toString()),
new Text("数字字符串转double:" + NumUtils.getDoubleByValueString(str2).toString()),
new Text("数字保留x位小数:" + NumUtils.getNumByValueString(str2,fractionDigits: 2).toString()),
new Text("浮点数字保留x位小数:" + NumUtils.getNumByValueDouble(d,2).toString()),
new Text("浮点数字保留x位小数:" + NumUtils.getNumByValueDouble(d,2).toString()),
new Text("判断是否是否是0:" + NumUtils.isZero(d).toString()),
new Text("两个数相加(防止精度丢失):" + NumUtils.addNum(d,d2).toString()),
new Text("两个数相减(防止精度丢失):" + NumUtils.subtractNum(d,d2).toString()),
new Text("两个数相乘(防止精度丢失):" + NumUtils.multiplyNum(d,d2).toString()),
new Text("两个数相除(防止精度丢失):" + NumUtils.divideNum(d,d2).toString()),
],
),
);
}
} | yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
example/lib/utils/object_utils_page.dart | Dart |
import 'package:flutter/material.dart';
import 'package:yc_flutter_utils/date/data_formats.dart';
import 'package:yc_flutter_utils/date/date_utils.dart';
import 'package:yc_flutter_utils/encrypt/encrypt_utils.dart';
import 'package:yc_flutter_utils/object/object_utils.dart';
class ObjectPage extends StatefulWidget {
ObjectPage();
@override
State<StatefulWidget> createState() {
return new _PageState();
}
}
class _PageState extends State<ObjectPage> {
String string = "yangchong";
List list1 = new List();
List list2 = null;
Map map1 = new Map();
Map map2 ;
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
list1.add("yangchong");
map1["name"] = "yangchong";
return Scaffold(
appBar: new AppBar(
title: new Text("EncryptUtils 加解密工具类"),
centerTitle: true,
),
body: new Column(
children: <Widget>[
new Text("判断字符串是否为空:" + ObjectUtils.isEmptyString(string).toString()),
new Text("判断集合是否为空:" + ObjectUtils.isEmptyList(list1).toString()),
new Text("判断字典是否为空:" + ObjectUtils.isEmptyMap(map1).toString()),
new Text("判断object对象是否为空:" + ObjectUtils.isEmpty(map1).toString()),
new Text("判断object是否不为空:" + ObjectUtils.isNotEmpty(map1).toString()),
new Text("比较两个集合是否相同:" + ObjectUtils.compareListIsEqual(list1,list2).toString()),
new Text("获取object的长度:" + ObjectUtils.getLength(string).toString()),
],
),
);
}
} | yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
example/lib/utils/other_utils_page.dart | Dart |
import 'package:flutter/material.dart';
import 'package:yc_flutter_utils/date/data_formats.dart';
import 'package:yc_flutter_utils/date/date_utils.dart';
import 'package:yc_flutter_utils/encrypt/encrypt_utils.dart';
import 'package:yc_flutter_utils/object/object_utils.dart';
import 'package:yc_flutter_utils/utils/platform_utils.dart';
import 'package:yc_flutter_utils/utils/random_utils.dart';
class OtherPage extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return new _PageState();
}
}
class _PageState extends State<OtherPage> {
String string = "yangchong";
List list1 = new List();
List list2 = null;
Map map1 = new Map();
Map map2 ;
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
list1.add("yangchong");
map1["name"] = "yangchong";
final value = PlatformUtils.select(
ios: "ios",
android: "android",
web: "web",
fuchsia: "fuchsia",
macOS: () => "macOS",
windows: () => "windows",
linux: () => "linux",
);
final valueFromFunction = PlatformUtils.select(
ios: () => "ios",
android: () => "android1",
web: () => "web",
fuchsia: () => "fuchsia",
);
return Scaffold(
appBar: new AppBar(
title: new Text("其他工具类"),
centerTitle: true,
),
body: new Column(
children: <Widget>[
new Text("生成一个表示十六进制颜色的随机整数:" + RandomUtils.randomColor().toString()),
new Text("生成指定长度或随机长度的随机字符串:" + RandomUtils.randomString(length: 6).toString()),
new Text("返回值或运行基于平台的函数 value: $value, valueFromFunction: $valueFromFunction"),
],
),
);
}
} | yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
example/lib/utils/parser_utils_page.dart | Dart | import 'package:flutter/material.dart';
import 'package:yc_flutter_utils/date/data_formats.dart';
import 'package:yc_flutter_utils/date/date_utils.dart';
import 'package:yc_flutter_utils/log/log_utils.dart';
import 'package:yc_flutter_utils/num/num_utils.dart';
import 'package:yc_flutter_utils/parsing/elements.dart';
import 'package:yc_flutter_utils/parsing/markup_utils.dart';
import 'package:yc_flutter_utils/sp/sp_utils.dart';
import 'package:yc_flutter_utils/toast/snack_utils.dart';
import 'package:yc_flutter_utils_example/model/city.dart';
import 'package:yc_flutter_utils/extens/extension_map.dart';
import 'package:shared_preferences/shared_preferences.dart';
class ParserPage extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return new _DatePageState();
}
}
class _DatePageState extends State<ParserPage> {
String markup1;
bool isWidget = false;
String markup2;
String markup3;
String editedMarkup4;
@override
void initState() {
super.initState();
String markup = """
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>title</title>
</head>
<body>
</body>
</html>
""";
markup1 = MarkupUtils.markup2json(markup).toJson();
String jsonString = r"""
{
"type": "root",
"children": [{
"type": "element",
"tag": "html",
"children": [{
"type": "element",
"tag": "head",
"children": [{
"type": "element",
"tag": "meta",
"attributes": [{
"name": "charset",
"value": "UTF-8",
"valueOriginal": "\"UTF-8\""
}]
}, {
"type": "element",
"tag": "title",
"children": [{
"type": "text",
"text": "title"
}]
}]
}, {
"type": "element",
"tag": "body"
}]
}]
}
""";
markup2 = MarkupUtils.jsonToMarkup(jsonString);
LogUtils.d(markup2,tag: "jsonToMarkup 2 :");
Node node3 = RootNode([
ElementNode(tag: "message", children: [
ElementNode(tag: "text", children: [TextNode("Hello!!")]),
ElementNode(tag: "from", children: [TextNode("Manoj sadhu")]),
CommentNode("A simple comment")
])
]);
markup3 = node3.toMarKup();
LogUtils.d(markup3,tag: "toMarKup 3 :");
node3.children.add(ElementNode(tag: "time", children: [TextNode("18-06-2019 09:18:00")]));
editedMarkup4 = node3.toMarKup();
LogUtils.d(editedMarkup4,tag: "toMarKup 4 :");
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: new AppBar(
title: new Text("Parser 解析工具类"),
centerTitle: true,
),
body: new ListView(
children: <Widget>[
new Text("将HTML/XML字符串转换为json 2 :" + markup1),
new Text("toMarKup 2 :" + markup2),
new Text("toMarKup 3 :" + markup3),
new Text("toMarKup 4 :" + editedMarkup4),
],
),
);
}
}
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
example/lib/utils/regex_utils_page.dart | Dart |
import 'package:flutter/material.dart';
import 'package:yc_flutter_utils/date/data_formats.dart';
import 'package:yc_flutter_utils/date/date_utils.dart';
import 'package:yc_flutter_utils/num/num_utils.dart';
import 'package:yc_flutter_utils/regex/regex_utils.dart';
class RegexPage extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return new _DatePageState();
}
}
class _DatePageState extends State<RegexPage> {
String str1 = "124321423";
String str2 = "1243.21423";
double d = 12312.3121;
double d2 = 12312.3121;
String card15 = "421142442342141";
String card18 = "421142442342141256";
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
DateTime dateTime = new DateTime.now();
return Scaffold(
appBar: new AppBar(
title: new Text("RegexUtils 正则校验工具类"),
centerTitle: true,
),
body: new Column(
children: <Widget>[
new Text("简单验证手机号:" + RegexUtils.isMobileSimple("13667225184").toString()),
new Text("精确验证手机号:" + RegexUtils.isMobileExact("13667225184").toString()),
new Text("验证电话号码:" + RegexUtils.isTel(str2).toString()),
new Text("验证身份证号码 15 位:" + RegexUtils.isIDCard15(card15).toString()),
new Text("简单验证身份证号码 18 位:" + RegexUtils.isIDCard18(card18).toString()),
new Text("精确验证身份证号码 18 位:" + RegexUtils.isIDCard18Exact(card18).toString()),
new Text("验证邮箱:" + RegexUtils.isEmail("yangchong211@163.com").toString()),
new Text("验证 URL:" + RegexUtils.isURL("https://github.com/yangchong211").toString()),
new Text("验证汉字:" + RegexUtils.isZh("逗比").toString()),
new Text("验证用户名:" + RegexUtils.isUserName(str1).toString()),
new Text("验证 IP 地址:" + RegexUtils.isIP("127.0.0.1").toString()),
],
),
);
}
} | yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
example/lib/utils/screen_utils_page.dart | Dart |
import 'package:flutter/material.dart';
import 'package:yc_flutter_utils/date/date_utils.dart';
import 'package:yc_flutter_utils/i18/template_time.dart';
import 'package:yc_flutter_utils/i18/extension.dart';
import 'package:yc_flutter_utils/screen/screen_utils.dart';
class ScreenPage extends StatefulWidget {
ScreenPage();
@override
State<StatefulWidget> createState() {
return new _PageState();
}
}
class _PageState extends State<ScreenPage> {
String screen = "初始化值";
@override
void initState() {
super.initState();
//延时500毫秒执行
Future.delayed(const Duration(milliseconds: 2500), () {
set(context);
});
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text("ScreenUtils 屏幕工具类"),
),
body: new Center(
child: new Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
new Text(screen),
],
),
));
}
void set(BuildContext context) {
ScreenUtils.instance.init(context);
var screenWidthDp = ScreenUtils.screenWidthDp;
var screenHeightDp = ScreenUtils.screenHeightDp;
var pixelRatio = ScreenUtils.pixelRatio;
var screenWidth = ScreenUtils.screenWidth;
var screenHeight = ScreenUtils.screenHeight;
var statusBarHeight = ScreenUtils.statusBarHeight;
var bottomBarHeight = ScreenUtils.bottomBarHeight;
var textScaleFactory = ScreenUtils.textScaleFactory;
screen =
"当前设备宽度 dp:"+screenWidthDp.toString() + "\n" +
"当前设备高度 dp:"+screenHeightDp.toString() + "\n" +
"设备的像素密度 :"+pixelRatio.toString() + "\n" +
"当前设备宽度 px:"+screenWidth.toString() + "\n" +
"当前设备高度 px:"+screenHeight.toString() + "\n" +
"底部安全区距离 dp:"+bottomBarHeight.toString() + "\n" +
"字体的缩放比例:"+textScaleFactory.toString() + "\n" +
"状态栏高度 dp:"+statusBarHeight.toString() + "\n"
;
setState(() {
});
}
} | yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
example/lib/utils/sp_utils_page.dart | Dart |
import 'package:flutter/material.dart';
import 'package:yc_flutter_utils/date/data_formats.dart';
import 'package:yc_flutter_utils/date/date_utils.dart';
import 'package:yc_flutter_utils/log/log_utils.dart';
import 'package:yc_flutter_utils/num/num_utils.dart';
import 'package:yc_flutter_utils/sp/sp_utils.dart';
import 'package:yc_flutter_utils/toast/snack_utils.dart';
import 'package:yc_flutter_utils_example/model/city.dart';
import 'package:yc_flutter_utils/extens/extension_map.dart';
import 'package:shared_preferences/shared_preferences.dart';
class SpPage extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return new _DatePageState();
}
}
class _DatePageState extends State<SpPage> {
String str1 = "124321423";
String str2 = "1243.21423";
double d = 12312.3121;
double d2 = 12312.3121;
List<String> list = new List();
List<dynamic> list2 = new List();
Map map = new Map();
bool isWidget = false;
bool putSuccess;
@override
void initState() {
super.initState();
list.add("yc");
list.add("doubi");
list2.add(1);
list2.add(true);
list2.add("yc");
map["1"] = "1";
map["2"] = "2";
LogUtils.i("initState 1 ");
Future(() async {
LogUtils.i("initState 2 ");
await SpUtils.init();
LogUtils.i("initState 3 ");
});
LogUtils.i("initState 4 ");
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: new AppBar(
title: new Text("sp存储工具类"),
centerTitle: true,
),
body: new ListView(
children: <Widget>[
new Text("先存储sp中存储的值:${putSuccess.toString()}"),
MaterialButton(
onPressed: put,
child: new Text("点击存储"),
color: Colors.cyan,
),
new Text("后获取sp中存储的值"),
MaterialButton(
onPressed: click,
child: new Text("点击获取"),
color: Colors.cyan,
),
getWidget(),
],
),
);
}
Widget getWidget(){
if(!isWidget){
return new Text("haha");
}
// return new Column(
// children: <Widget>[
// new Text("获取sp中key的布尔值:" + sharedPreferences.getBool("100").toString()),
// new Text("获取sp中key的double值:" + sharedPreferences.getDouble("101").toString()),
// new Text("获取sp中key的int值:" + sharedPreferences.getInt("102").toString()),
// new Text("获取sp中key的字符串:" + sharedPreferences.getString("103").toString()),
// new Text("获取sp中key的list<String>值:" + sharedPreferences.getStringList("104").toString()),
// ],
// );
return new Column(
children: <Widget>[
new Text("获取sp中key的布尔值:" + SpUtils.getBool("100").toString()),
new Text("获取sp中key的double值:" + SpUtils.getDouble("101").toString()),
new Text("获取sp中key的int值:" + SpUtils.getInt("102").toString()),
new Text("获取sp中key的字符串:" + SpUtils.getString("103").toString()),
new Text("获取sp中key的list<String>值:" + SpUtils.getStringList("104").toString()),
new Text("获取sp中key的dynamic值:" + SpUtils.getDynamic("102").toString()),
new Text("获取sp中key的map值:" + SpUtils.getStringMap("106").toString()),
new Text("获取sp中key的list:" + SpUtils.getStringList(str1).toString()),
new Text("获取sp中key的map数据:" + SpUtils.getObject("107").toJsonString()),
new Text("获取sp中key的list集合:" + SpUtils.getObjectList("108").toString()),
],
);
}
void click() {
setState(() {
isWidget = true;
});
}
// SharedPreferences sharedPreferences;
void put() async{
// sharedPreferences = await SharedPreferences.getInstance();
// sharedPreferences.setBool("100", true);
// sharedPreferences.setDouble("101", 101.1);
// sharedPreferences.setInt("102", 520);
// sharedPreferences.setString("103", "yangchong");
// sharedPreferences.setStringList("104", list);
await SpUtils.init();
SpUtils.putBool("100", true).then((value){
if(value){
putSuccess = true;
} else {
putSuccess = false;
}
});
SpUtils.putDouble("101", 101.1);
SpUtils.putInt("102", 520);
SpUtils.putString("103", "yangchong");
SpUtils.putStringList("104", list);
SpUtils.putStringList2("105", list2);
SpUtils.putStringMap("106", map).then((value){
if(value){
putSuccess = true;
} else {
putSuccess = false;
}
});
/// 存储实体对象示例。
City city = new City("湖北黄冈");
SpUtils.putObject("107", city);
/// 存储实体对象list示例。
List<City> list5 = new List();
list5.add(new City("黄冈市"));
list5.add(new City("北京市"));
SpUtils.putObjectList("108", list5);
setState(() {
});
}
} | yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
example/lib/utils/storage_utils_page.dart | Dart |
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:yc_flutter_utils/file/storage_utils.dart';
class StoragePage extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return new _PageState();
}
}
class _PageState extends State<StoragePage> {
String get1;
String get2;
String get3;
String string1;
String string2;
String string3;
String string4;
String string5;
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: new AppBar(
title: new Text("StorageUtils 文件管理工具类"),
centerTitle: true,
),
body: new ListView(
children: <Widget>[
MaterialButton(
onPressed: getClick1,
child: new Text("设备上临时目录的路径"),
color: Colors.cyan,
),
new Text("设备上临时目录的路径:$get1"),
MaterialButton(
onPressed: getClick2,
child: new Text("获取应用程序的目录"),
color: Colors.cyan,
),
new Text("获取应用程序的目录:$get2"),
MaterialButton(
onPressed: getClick3,
child: new Text("应用程序可以访问顶层存储的目录的路径"),
color: Colors.cyan,
),
new Text("应用程序可以访问顶层存储的目录的路径:$get3"),
MaterialButton(
onPressed: click1,
child: new Text("同步创建文件夹"),
color: Colors.cyan,
),
new Text("同步创建文件夹:$string1"),
MaterialButton(
onPressed: click2,
child: new Text("异步创建文件夹"),
color: Colors.cyan,
),
new Text("异步创建文件夹:$string2"),
MaterialButton(
onPressed: click3,
child: new Text("创建临时目录"),
color: Colors.cyan,
),
new Text("创建临时目录文件:$string3"),
MaterialButton(
onPressed: click4,
child: new Text("创建临时目录"),
color: Colors.cyan,
),
new Text("创建应用目录文件:$string4"),
],
),
);
}
void getClick1() async{
String appDocDir = await StorageUtils.getTempPath();
setState(() {
get1 = appDocDir;
});
}
void getClick2() async{
String appDocDir = await StorageUtils.getAppDocPath();
setState(() {
get2 = appDocDir;
});
}
void getClick3() async{
String appDocDir = await StorageUtils.getStoragePath();
setState(() {
get3= appDocDir;
});
}
void click1() async{
String appDocDir = await StorageUtils.getTempPath();
String filePath = appDocDir + '/yc.json';
Directory createAppDocDir = await StorageUtils.createDirSync(filePath);
setState(() {
string1 = "路径" + createAppDocDir.path;
});
}
void click2() async{
String appDocDir = await StorageUtils.getTempPath();
String filePath = appDocDir + '/doubi.json';
var createDir = StorageUtils.createDir(filePath);
setState(() {
string2 = createDir.path;
});
}
void click3() async{
Directory appDocDir = await StorageUtils.createTempDir(dirName: "haha.txt");
setState(() {
string3 = appDocDir.path;
});
}
void click4() async {
Directory appDocDir = await StorageUtils.createAppDocDir(dirName: "haha.txt");
setState(() {
string4 = appDocDir.path;
});
}
void click5() {
}
void click6() {
}
} | yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
example/lib/utils/system_utils_page.dart | Dart |
import 'package:flutter/material.dart';
import 'package:yc_flutter_utils/date/data_formats.dart';
import 'package:yc_flutter_utils/date/date_utils.dart';
import 'package:yc_flutter_utils/log/log_utils.dart';
import 'package:yc_flutter_utils/num/num_utils.dart';
import 'package:yc_flutter_utils/sp/sp_utils.dart';
import 'package:yc_flutter_utils/system/system_utils.dart';
import 'package:yc_flutter_utils/toast/snack_utils.dart';
import 'package:yc_flutter_utils_example/model/city.dart';
import 'package:yc_flutter_utils/extens/extension_map.dart';
import 'package:shared_preferences/shared_preferences.dart';
class SystemPage extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return new _DatePageState();
}
}
class _DatePageState extends State<SystemPage> {
String str1 = "124321423";
String str2 = "1243.21423";
double d = 12312.3121;
double d2 = 12312.3121;
List<String> list = new List();
List<dynamic> list2 = new List();
Map map = new Map();
bool isWidget = false;
bool putSuccess;
@override
void initState() {
super.initState();
list.add("yc");
list.add("doubi");
list2.add(1);
list2.add(true);
list2.add("yc");
map["1"] = "1";
map["2"] = "2";
LogUtils.i("initState 1 ");
Future(() async {
LogUtils.i("initState 2 ");
await SpUtils.init();
LogUtils.i("initState 3 ");
});
LogUtils.i("initState 4 ");
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: new AppBar(
title: new Text("sp存储工具类"),
centerTitle: true,
),
body: new ListView(
children: <Widget>[
MaterialButton(
onPressed: click1,
child: new Text("剪切到剪切板"),
color: Colors.cyan,
),
MaterialButton(
onPressed: click2,
child: new Text("隐藏软键盘"),
color: Colors.cyan,
),
MaterialButton(
onPressed: click3,
child: new Text("打开软键盘"),
color: Colors.cyan,
),
MaterialButton(
onPressed: click4,
child: new Text("清除数据"),
color: Colors.cyan,
),
],
),
);
}
void click1() {
SystemUtils.copyToClipboard("你好");
}
void click2() {
SystemUtils.hideKeyboard();
}
void click3() {
SystemUtils.showKeyboard();
}
void click4() {
SystemUtils.clearClientKeyboard();
}
} | yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
example/lib/utils/text_utils_page.dart | Dart |
import 'package:flutter/material.dart';
import 'package:yc_flutter_utils/date/data_formats.dart';
import 'package:yc_flutter_utils/date/date_utils.dart';
import 'package:yc_flutter_utils/encrypt/encrypt_utils.dart';
import 'package:yc_flutter_utils/object/object_utils.dart';
import 'package:yc_flutter_utils/text/text_utils.dart';
class TextPage extends StatefulWidget {
TextPage();
@override
State<StatefulWidget> createState() {
return new _PageState();
}
}
class _PageState extends State<TextPage> {
String string = "yangchong";
String h = "yang,chong";
List list1 = new List();
List list2 = null;
Map map1 = new Map();
Map map2 ;
String card = "632912783288887";
String phone = "13667225184";
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
list1.add("yangchong");
map1["name"] = "yangchong";
return Scaffold(
appBar: new AppBar(
title: new Text("EncryptUtils 加解密工具类"),
centerTitle: true,
),
body: new Column(
children: <Widget>[
new Text("判断文本内容是否为空:" + TextUtils.isEmpty(string).toString()),
new Text("判断字符串是以ya开头:" + TextUtils.startsWith(string,"ya").toString()),
new Text("判断字符串是否包含ya:" + TextUtils.contains(string,"ya").toString()),
new Text("判断字符串是否包含ya:" + TextUtils.abbreviate(string,4).toString()),
new Text("判断字符串是否包含ya:" + TextUtils.abbreviate(string,7).toString()),
new Text("比较两个字符串是否相同:" + TextUtils.compare(string,"hah").toString()),
new Text("比较两个字符串是否相同:" + TextUtils.compare("hah","hah").toString()),
new Text("比较两个字符串是否相同:" + TextUtils.hammingDistance("yangchong","chongyang").toString()),
new Text("格式化银行卡:" + TextUtils.formatDigitPattern(card).toString()),
new Text("格式化手机号,从后面开始:" + TextUtils.formatDigitPatternEnd(phone).toString()),
new Text("每隔4位加空格:" + TextUtils.formatSpace4(card).toString()),
new Text("每隔3三位加逗号:" + TextUtils.formatComma3(phone).toString()),
new Text("隐藏手机号中间n位:" + TextUtils.hideNumber(phone).toString()),
new Text("隐藏手机号中间n位:" + TextUtils.hideNumber(phone,start: 2,end: 5).toString()),
new Text("按照正则切割字符串:" + TextUtils.split(h,",").toString()),
new Text("反转字符串:" + TextUtils.reverse(string).toString()),
],
),
);
}
} | yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
example/lib/utils/timer_utils_page.dart | Dart | import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:yc_flutter_utils/file/file_utils.dart';
import 'package:yc_flutter_utils/timer/timer_utils.dart';
class TimerPage extends StatefulWidget {
@override
State<StatefulWidget> createState() => StorageState();
}
class StorageState extends State<TimerPage> {
bool play = false;
String string1 = "null";
@override
void dispose() {
super.dispose();
stop();
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('TimerUtils 计时器'),
),
body: new ListView(
children: <Widget>[
new Text("倒计时器 :$string1"),
MaterialButton(
onPressed: start,
child: new Text("开始倒计时"),
color: Colors.cyan,
),
new Text("开启timer倒计时:$string1"),
MaterialButton(
onPressed: stop,
child: new Text("停止计时器"),
color: Colors.cyan,
),
],
),
);
}
TimerUtils timerUtils = null;
void start() {
stop();
//timerUtils = new TimerUtils(mInterval: 1000,mTotalTime: 60);
timerUtils = new TimerUtils();
timerUtils.setTotalTime(60);
timerUtils.setInterval(1000);
timerUtils.startTimer();
timerUtils.setOnTimerTickCallback((millisUntilFinished) {
setState(() {
string1 = millisUntilFinished.toString();
});
});
}
void stop() {
if(timerUtils!=null){
timerUtils.cancel();
}
}
}
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
example/lib/widget/common_widget.dart | Dart | // import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
/**
* 封装CommonWidget的思想类似java里的构造者模式,可以让widget直接实现链式调用
*/
class CommonWidget {
Widget _widget;
Function _onTapFunc;
Function _onDoubleTapFunc;
Function _onLongPressFunc;
CommonWidget(Widget widget) {
this._widget = widget;
}
///add padding属性
CommonWidget padding(
{Key key, double left = 0.0, double top = 0.0, double right = 0.0, double bottom = 0.0}) {
var padding = EdgeInsets.only(left: left, top: top, right: right, bottom: bottom);
_widget = new Padding(key: key, padding: padding, child: _widget);
return this;
}
///增加padingall
CommonWidget paddAll({Key key, double all = 0.0}) {
var padding = EdgeInsets.all(all);
_widget = new Padding(key: key, padding: padding, child: _widget);
return this;
}
///增加align 当前布局相对位置
///FractionalOffset.centerRight
CommonWidget align({Key key, AlignmentGeometry alignment = Alignment.center}) {
_widget = new Align(key: key, alignment: alignment, child: _widget);
return this;
}
///位置
CommonWidget positioned(
{Key key,
double left,
double top,
double right,
double bottom,
double width,
double height}) {
_widget = new Positioned(
key: key,
left: left,
top: top,
right: right,
bottom: bottom,
width: width,
height: height,
child: _widget);
return this;
}
///stack 相当于frameLayout布局
///填充布局
CommonWidget expanded({Key key, int flex = 1}) {
_widget = new Expanded(key: key, flex: flex, child: _widget);
return this;
}
///是否显示布局 true为不显示 false为显示
CommonWidget offstage({Key key, bool offstage = true}) {
_widget = new Offstage(key: key, offstage: offstage, child: _widget);
return this;
}
///透明度 0 是完全透明 1 完全不透明
CommonWidget opacity({Key key, @required double opacity, alwaysIncludeSemantics = false}) {
_widget = new Opacity(
key: key, opacity: opacity, alwaysIncludeSemantics: alwaysIncludeSemantics, child: _widget);
return this;
}
///基准线布局
CommonWidget baseline({
Key key,
@required double baseline,
@required TextBaseline baselineType,
}) {
_widget =
new Baseline(key: key, baseline: baseline, baselineType: baselineType, child: _widget);
return this;
}
///设置宽高比
CommonWidget aspectRatio({Key key, @required double aspectRatio}) {
_widget = new AspectRatio(key: key, aspectRatio: aspectRatio, child: _widget);
return this;
}
///矩阵转换
CommonWidget transform({
Key key,
@required Matrix4 transform,
origin,
alignment,
transformHitTests = true,
}) {
_widget = new Transform(
key: key,
transform: transform,
origin: origin,
alignment: alignment,
transformHitTests: transformHitTests,
child: _widget);
return this;
}
///居中 todo: center
CommonWidget center({Key key, double widthFactor, double heightFactor}) {
_widget =
new Center(key: key, widthFactor: widthFactor, heightFactor: heightFactor, child: _widget);
return this;
}
///布局容器
CommonWidget container({
Key key,
alignment,
padding,
Color color,
Decoration decoration,
foregroundDecoration,
double width,
double height,
BoxConstraints constraints,
margin,
transform,
}) {
_widget = new Container(
key: key,
alignment: alignment,
padding: padding,
color: color,
decoration: decoration,
foregroundDecoration: foregroundDecoration,
width: width,
height: height,
constraints: constraints,
margin: margin,
transform: transform,
child: _widget);
return this;
}
///设置具体尺寸
CommonWidget sizedBox({Key key, double width, double height}) {
_widget = new SizedBox(key: key, width: width, height: height, child: _widget);
return this;
}
///设置最大最小宽高布局
CommonWidget constrainedBox({
Key key,
minWidth = 0.0,
maxWidth = double.infinity,
minHeight = 0.0,
maxHeight = double.infinity,
}) {
BoxConstraints constraints = new BoxConstraints(
minWidth: minWidth, maxWidth: maxWidth, minHeight: minHeight, maxHeight: maxHeight);
_widget = new ConstrainedBox(key: key, constraints: constraints, child: _widget);
return this;
}
///限定最大宽高布局
CommonWidget limitedBox({
Key key,
maxWidth = double.infinity,
maxHeight = double.infinity,
}) {
_widget = new LimitedBox(key: key, maxWidth: maxWidth, maxHeight: maxHeight, child: _widget);
return this;
}
///百分比布局
CommonWidget fractionallySizedBox(
{Key key, alignment = Alignment.center, double widthFactor, double heightFactor}) {
_widget = new FractionallySizedBox(
key: key,
alignment: alignment,
widthFactor: widthFactor,
heightFactor: heightFactor,
child: _widget);
return this;
}
///缩放布局
CommonWidget fittedBox({Key key, fit = BoxFit.contain, alignment = Alignment.center}) {
_widget = new FittedBox(key: key, fit: fit, alignment: alignment, child: _widget);
return this;
}
///旋转盒子 1次是90度
CommonWidget rotatedBox({
Key key,
@required int quarterTurns,
}) {
_widget = new RotatedBox(key: key, quarterTurns: quarterTurns, child: _widget);
return this;
}
///装饰盒子 细节往外抛 decoration 编写放在外面
CommonWidget decoratedBox({
Key key,
@required Decoration decoration,
position = DecorationPosition.background,
}) {
_widget =
new DecoratedBox(key: key, decoration: decoration, position: position, child: _widget);
return this;
}
///圆形剪裁
CommonWidget clipOval(
{Key key, CustomClipper<Rect> clipper, Clip clipBehavior = Clip.antiAlias}) {
_widget = new ClipOval(key: key, clipper: clipper, clipBehavior: clipBehavior, child: _widget);
return this;
}
///圆角矩形剪裁
CommonWidget clipRRect(
{Key key,
@required BorderRadius borderRadius,
CustomClipper<RRect> clipper,
Clip clipBehavior = Clip.antiAlias}) {
_widget = new ClipRRect(
key: key,
borderRadius: borderRadius,
clipper: clipper,
clipBehavior: clipBehavior,
child: _widget);
return this;
}
///矩形剪裁 todo: 需要自定义clipper 否则无效果
CommonWidget clipRect(
{Key key, @required CustomClipper<Rect> clipper, Clip clipBehavior = Clip.hardEdge}) {
_widget = new ClipRect(key: key, clipper: clipper, clipBehavior: clipBehavior, child: _widget);
return this;
}
///路径剪裁 todo: 需要自定义clipper 否则无效果
CommonWidget clipPath(
{Key key, @required CustomClipper<Path> clipper, Clip clipBehavior = Clip.antiAlias}) {
_widget = new ClipPath(key: key, clipper: clipper, clipBehavior: clipBehavior, child: _widget);
return this;
}
///animatedOpacity 淡入淡出
CommonWidget animatedOpacity({
Key key,
@required double opacity,
Curve curve = Curves.linear,
@required Duration duration,
}) {
_widget = new AnimatedOpacity(
key: key, opacity: opacity, curve: curve, duration: duration, child: _widget);
return this;
}
///页面简单切换效果
CommonWidget hero({Key key, @required Object tag}) {
_widget = new Hero(key: key, tag: tag, child: _widget);
return this;
}
///点击事件
CommonWidget onClick({Key key, onTap, onDoubleTap, onLongPress}) {
_widget = new GestureDetector(
key: key,
child: _widget,
onTap: onTap ?? _onTapFunc,
onDoubleTap: onDoubleTap ?? _onDoubleTapFunc,
onLongPress: onLongPress ?? _onLongPressFunc,
);
return this;
}
///添加点击事件
CommonWidget onTap(Function func, {Key key}) {
_onTapFunc = func;
_widget = new GestureDetector(
key: key,
child: _widget,
onTap: _onTapFunc,
onDoubleTap: _onDoubleTapFunc,
onLongPress: _onLongPressFunc,
);
return this;
}
///双击
CommonWidget onDoubleTap(Function func, {Key key}) {
_onDoubleTapFunc = func;
_widget = new GestureDetector(
key: key,
child: _widget,
onTap: _onTapFunc,
onDoubleTap: _onDoubleTapFunc,
onLongPress: _onLongPressFunc,
);
return this;
}
///长按
CommonWidget onLongPress(Function func, {Key key}) {
_onLongPressFunc = func;
_widget = new GestureDetector(
key: key,
child: _widget,
onTap: _onTapFunc,
onDoubleTap: _onDoubleTapFunc,
onLongPress: _onLongPressFunc,
);
return this;
}
Widget build() {
return _widget;
}
}
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
example/lib/widget/custom_raised_button.dart | Dart | import 'package:flutter/material.dart';
import 'package:yc_flutter_utils/router/navigator_utils.dart';
//定义自带路由跳转button
// ignore: must_be_immutable
class CustomRaisedButton extends StatelessWidget {
var _shapeBorder = new RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(20.0)));
var _textStyle = new TextStyle(color: Colors.white, fontSize: 16.0);
var _btnTitle;
var _pageNavigator;
CustomRaisedButton(this._pageNavigator, this._btnTitle);
@override
Widget build(BuildContext context) {
return RaisedButton(
onPressed: () {
//第一种写法
//Navigator.push(context, new MaterialPageRoute(builder: (context) => _pageNavigator));
//第二张路由写法
// Navigator.of(context)
// .push(new MaterialPageRoute(builder: (context) => _pageNavigator));
NavigatorUtils.push(context, _pageNavigator);
},
child: Text(
_btnTitle,
style: _textStyle,
),
color: Colors.lightGreen,
highlightColor: Colors.green,
shape: _shapeBorder,
);
}
}
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
example/test/widget_test.dart | Dart | // This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility that Flutter provides. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Verify Platform version', (WidgetTester tester) async {
// Build our app and trigger a frame.
// await tester.pumpWidget(MyApp());
// Verify that platform version is retrieved.
expect(
find.byWidgetPredicate(
(Widget widget) => widget is Text &&
widget.data.startsWith('Running on:'),
),
findsOneWidget,
);
});
}
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
ios/Classes/YcFlutterUtilsPlugin.h | C/C++ Header | #import <Flutter/Flutter.h>
@interface YcFlutterUtilsPlugin : NSObject<FlutterPlugin>
@end
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
ios/Classes/YcFlutterUtilsPlugin.m | Objective-C | #import "YcFlutterUtilsPlugin.h"
@implementation YcFlutterUtilsPlugin
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
FlutterMethodChannel* channel = [FlutterMethodChannel
methodChannelWithName:@"yc_flutter_utils"
binaryMessenger:[registrar messenger]];
YcFlutterUtilsPlugin* instance = [[YcFlutterUtilsPlugin alloc] init];
[registrar addMethodCallDelegate:instance channel:channel];
}
- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result {
if ([@"getPlatformVersion" isEqualToString:call.method]) {
result([@"iOS " stringByAppendingString:[[UIDevice currentDevice] systemVersion]]);
} else {
result(FlutterMethodNotImplemented);
}
}
@end
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/base/base_constants.dart | Dart | ///存储所有通信key
class BaseConstants {
}
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/base/base_method_constants.dart | Dart | ///存储所有通信method的方法名称
class BaseMethodConstants {
}
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/bus/event_bus_helper.dart | Dart |
//定义一个top-level(全局)变量,页面引入该文件后可以直接使用bus
var bus = new EventBusHelper();
//订阅者回调签名
typedef void EventCallback(arg);
class EventBusHelper {
//私有构造函数
EventBusHelper._internal();
//保存单例
static EventBusHelper _singleton = new EventBusHelper._internal();
//工厂构造函数
factory EventBusHelper()=> _singleton;
//保存事件订阅者队列,key:事件名(id),value: 对应事件的订阅者队列
var _emap = new Map<Object, List<EventCallback>>();
//添加订阅者
void on(eventName, EventCallback f) {
if (eventName == null || f == null) return;
_emap[eventName] ??= new List<EventCallback>();
_emap[eventName].add(f);
}
//移除订阅者
void off(eventName, [EventCallback f]) {
var list = _emap[eventName];
if (eventName == null || list == null) return;
if (f == null) {
_emap[eventName] = null;
} else {
list.remove(f);
}
}
//触发事件,事件触发后该事件所有订阅者会被调用
void emit(eventName, [arg]) {
var list = _emap[eventName];
if (list == null) return;
int len = list.length - 1;
//反向遍历,防止订阅者在回调中移除自身带来的下标错位
for (var i = len; i > -1; --i) {
list[i](arg);
}
}
}
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/bus/event_bus_service.dart | Dart |
import 'dart:async';
typedef void EventCallback(arg);
/// 消息结构体
class EventMessage {
final String eventName;
final dynamic arguments;
EventMessage(this.eventName, {this.arguments});
}
/// 消息通知服务
class EventBusService {
factory EventBusService() => _getInstance();
static EventBusService get instance => _getInstance();
static EventBusService _instance;
EventBusService._internal();
static EventBusService _getInstance() {
if (_instance == null) {
_instance = EventBusService._internal();
}
return _instance;
}
EventBus _eBus = EventBus();
EventBus get eventBus {
return _eBus;
}
}
class EventBus {
StreamController _streamController;
StreamController get streamController => _streamController;
EventBus({bool sync = false})
: _streamController = StreamController.broadcast(sync: sync);
EventBus.customController(StreamController controller)
: _streamController = controller;
///监听事件
Stream<T> on<T>() {
if (T == dynamic) {
return streamController.stream;
} else {
return streamController.stream.where((event) => event is T).cast<T>();
}
}
///添加事件
void fire(event) {
streamController.add(event);
}
///移除事件
void destroy() {
_streamController.close();
}
}
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/byte/byte.dart | Dart |
class Byte {
int _byte = 0;
int get value => _byte;
Byte(int value) {
_byte = value & 0xFF;
}
@override
String toString() {
return '0x' + (_byte.toRadixString(16).padLeft(2, '0').toUpperCase());
}
}
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/byte/byte_array.dart | Dart | import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:yc_flutter_utils/byte/byte.dart';
import 'package:yc_flutter_utils/byte/byte_utils.dart';
/// 字节数组
class ByteArray {
Uint8List _bytes = Uint8List(0);
/// bytes in UInt8List
Uint8List get bytes => _bytes;
/// bytes in List<Byte>
List<Byte> get array => _bytes.map((byte) => Byte(byte)).toList();
ByteArray(Uint8List array) {
_bytes = Uint8List.fromList(array);
}
/// 从字节数组中提取数值
ByteArray.fromByte(int value) {
_bytes = _toArray(value);
}
/// 合并两个字节
ByteArray.combineArrays(Uint8List array1, Uint8List array2) {
_bytes = ByteUtils.combine(arrayFirst: array1, arraySecond: array2);
}
/// 合并某个值到字节数组,value放到最后
ByteArray.combine1(Uint8List array, int value) {
_bytes = ByteUtils.combine(arrayFirst: array, arraySecond: _toArray(value));
}
/// 合并某个值到数据,value放到最前
ByteArray.combine2(int value, Uint8List array) {
_bytes = ByteUtils.combine(arrayFirst: _toArray(value), arraySecond: array);
}
/// 添加某个值到字节数组
Uint8List append(int value) {
_bytes = ByteUtils.combine(arrayFirst: _bytes, arraySecond: _toArray(value));
return _bytes;
}
Uint8List appendArray(Uint8List array) {
_bytes = ByteUtils.combine(arrayFirst: _bytes, arraySecond: array);
return _bytes;
}
Uint8List insert({@required int indexStart, @required int value}) {
_bytes = ByteUtils.insert(origin: _bytes,
indexStart: indexStart, arrayInsert: Uint8List.fromList([value]));
return _bytes;
}
Uint8List insertArray(
{@required int indexStart, @required Uint8List arrayInsert}) {
_bytes = ByteUtils.insert(origin: _bytes,
indexStart: indexStart, arrayInsert: arrayInsert);
return _bytes;
}
Uint8List remove({@required int indexStart, @required int lengthRemove}) {
_bytes = ByteUtils.remove(origin: _bytes,
indexStart: indexStart, lengthRemove: lengthRemove);
return _bytes;
}
Uint8List _toArray(int value) {
return Uint8List.fromList([value]);
}
}
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/byte/byte_double_word.dart | Dart | import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'byte.dart';
class ByteDoubleWord {
Byte _one = Byte(0);
Byte _two = Byte(0);
Byte _three = Byte(0);
Byte _four = Byte(0);
ByteDoubleWord({@required Byte one, @required Byte two,
@required Byte three, @required Byte four}) {
_one = one;
_two = two;
_three = three;
_four = four;
}
ByteDoubleWord.fromInt(int value) {
_four = Byte(value >> 24);
_three = Byte(value >> 16);
_two = Byte(value >> 8);
_one = Byte(value);
}
Uint8List get bytes =>
Uint8List.fromList([_one.value, _two.value, _three.value, _four.value]);
@override
String toString() {
return _four.toString() +
',' + _three.toString() +
',' + _two.toString() +
',' + _one.toString();
}
}
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/byte/byte_utils.dart | Dart |
import 'dart:convert';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:yc_flutter_utils/flutter_utils.dart';
/// Radix: hex&dec
enum Radix {
hex,
dec,
}
/// 字节工具类
class ByteUtils {
ByteUtils._();
/// 将可读字符串转换为字节数组,用空格或逗号分隔的字节。
/// 默认的基数是十六进制,或者指定的基数
/// 比如:'01 02, ff 0x10,0xfa , 90 76 AF a0'
/// 输出:[1, 2, 255, 16, 250, 144, 118, 175, 160]
static Uint8List fromReadable(String readable, {Radix radix = Radix.hex}) {
if(TextUtils.isEmpty(readable)){
return null;
}
final List<int> list = [];
final split = RegExp(' +');
final strArray = readable.replaceAll(',', ' ').split(split);
for (String str in strArray) {
var pure = str.trim();
if (radix == Radix.hex && pure.startsWith('0x')) {
pure = pure.substring(2);
}
final value = int.tryParse(pure, radix: radix == Radix.hex ? 16 : 10);
if (value == null) return null;
list.add(value);
}
if (list.length <= 0) return null;
return Uint8List.fromList(list);
}
/// 将字节数组转换为可读字符串。
/// 默认基数是十六进制,或指定的基数
static String toReadable(Uint8List buffer, {Radix radix = Radix.hex}) {
if (buffer == null || buffer.length <= 0) return '';
final List<String> list = [];
for (int data in buffer) {
var str =
data.toRadixString(radix == Radix.hex ? 16 : 10).padLeft(2, '0');
if (radix == Radix.hex) str = ('0x' + str.toUpperCase());
list.add(str);
}
final result = list.join(' ');
return result;
}
/// 将字节数组转换为base64字符串
static String toBase64(Uint8List buffer) {
final str = base64Encode(buffer);
return str;
}
/// 转换base64字符串到字节数组
static Uint8List fromBase64(String base64) {
final data = base64Decode(base64);
return data;
}
/// 克隆字节数组
static Uint8List clone(Uint8List origin) {
return Uint8List.fromList(origin);
}
/// 判断两个字节是否相同
static bool same(Uint8List bytes1, Uint8List bytes2) {
if (bytes1.length != bytes2.length) return false;
for (int i = 0; i < bytes1.length; i++) {
if (bytes1[i] != bytes2[i]) return false;
}
return true;
}
/// 从字节序列中提取数据
static Uint8List extract({@required Uint8List origin,
@required int indexStart, @required int length}) {
if (indexStart >= origin.length) return null;
int end = indexStart + length;
if (end >= origin.length) {
end = origin.length;
}
final sub = origin.sublist(indexStart, end);
return sub;
}
/// 将两个字节拼接
static Uint8List combine({@required Uint8List arrayFirst,
@required Uint8List arraySecond}) {
return insert(origin: arrayFirst, indexStart: arrayFirst.length,
arrayInsert: arraySecond);
}
/// 在字节某个索引处插入字节
static Uint8List insert({@required Uint8List origin,
@required int indexStart, @required Uint8List arrayInsert}) {
if (indexStart < 0 || arrayInsert.length <= 0) return origin;
if (origin.length == 0) {
return Uint8List.fromList(arrayInsert);
}
final actIndex = indexStart > origin.length ? origin.length : indexStart;
var list = List<int>.from(origin);
list.insertAll(actIndex, arrayInsert);
return Uint8List.fromList(list);
}
/// 在字节某个索引处移除字节
static Uint8List remove({@required Uint8List origin,
@required int indexStart, @required int lengthRemove}) {
if (indexStart < 0 || lengthRemove <= 0) return origin;
if (origin.length == 0) return origin;
if (indexStart >= origin.length) return origin;
final actEnd = (indexStart + lengthRemove > origin.length)
? origin.length
: (indexStart + lengthRemove);
var list = List<int>.from(origin);
list.removeRange(indexStart, actEnd);
return Uint8List.fromList(list);
}
}
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/byte/byte_word.dart | Dart | import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'byte.dart';
class ByteWord {
Byte _high = Byte(0);
Byte _low = Byte(0);
Byte get high => _high;
Byte get low => _low;
ByteWord({@required Byte high, @required Byte low}) {
_high = high;
_low = low;
}
ByteWord.fromInt(int value) {
_high = Byte(value >> 8);
_low = Byte(value);
}
/// low at first, high at second.
/// little-endian
Uint8List get bytes => Uint8List.fromList([_low.value, _high.value]);
@override
String toString() {
return _high.toString() + ',' + _low.toString();
}
}
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/calcu/calculate_utils.dart | Dart |
import 'package:flutter/material.dart';
/// 计算工具类
class CalculateUtils {
/// 计算文本高度
static double calculateTextHeight(BuildContext context,String value,
fontSize, FontWeight fontWeight,
double maxWidth, int maxLines) {
//创建painter
TextPainter painter = TextPainter(
locale: Localizations.localeOf(context, nullOk: true),
maxLines: maxLines,
textDirection: TextDirection.ltr,
text: TextSpan(
text: value,
style: TextStyle(
fontWeight: fontWeight,
fontSize: fontSize,
),
),
);
painter.layout(maxWidth: maxWidth);
return painter.height;
}
/// 计算文本宽度
static double calculateTextWidth(BuildContext context,String value,
fontSize, FontWeight fontWeight,
double maxWidth, int maxLines) {
//创建painter
TextPainter painter = TextPainter(
locale: Localizations.localeOf(context, nullOk: true),
maxLines: maxLines,
textDirection: TextDirection.ltr,
text: TextSpan(
text: value,
style: TextStyle(
fontWeight: fontWeight,
fontSize: fontSize,
),
),
);
painter.layout(maxWidth: maxWidth);
return painter.width;
}
} | yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/color/color_utils.dart | Dart |
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:yc_flutter_utils/log/log_utils.dart';
import 'package:yc_flutter_utils/object/object_utils.dart';
import 'package:yc_flutter_utils/regex/regex_constants.dart';
import 'package:yc_flutter_utils/regex/regex_utils.dart';
import 'package:yc_flutter_utils/text/text_utils.dart';
///颜色工具类
class ColorUtils{
///颜色值通常遵循RGB/ARGB标准
///使用时通常以“ # ”字符开头的8位16进制表示
///其中ARGB 依次代表透明度(Alpha)、红色(Red)、绿色(Green)、蓝色(Blue)
///RGB/ARGB(A表示透明度)
///RGB #RGB888
///ARGB #00RGB888
///字符串转换成color
static Color hexToColor(String color, {Color defaultColor}) {
if (color == null || color.length != 7 ||
int.tryParse(color.substring(1, 7), radix: 16) == null) {
return defaultColor;
}
var parse = int.parse(color.substring(1, 7), radix: 16);
var hexColor = Color(parse + 0xFF000000);
LogUtils.d("color hex to : ${hexColor.toString()}");
return hexColor;
}
///将颜色转化为color
static Color toColor(String color , {Color defaultColor}) {
if (TextUtils.isEmpty(color)) {
return defaultColor;
}
if (!color.contains("#")) {
return defaultColor;
}
var hexColor = color.replaceAll("#", "");
//如果是6位,前加0xff
if (hexColor.length == 6) {
hexColor = "0xff" + hexColor;
var color = Color(int.parse(hexColor));
LogUtils.d("to color 6 : ${color.toString()}");
return color;
}
//如果是8位,前加0x
if (hexColor.length == 8) {
var color = Color(int.parse("0x$hexColor"));
LogUtils.d("to color 8 : ${color.toString()}");
return color;
}
LogUtils.d("to color : ${hexColor.toString()}");
return defaultColor;
}
/// 将color颜色转变为字符串
static String colorString(Color color){
if(ObjectUtils.isNull(color)){
return null;
}
int value = color.value;
String radixString = value.toRadixString(16);
String colorString = radixString.padLeft(8, '0').toUpperCase();
return "#$colorString";
}
/// 检查字符串是否为十六进制
/// Example: HexColor => #12F
static bool isHexadecimal(String color) {
return RegexUtils.hasMatch(color, RegexConstants.hexadecimal);
}
static Color hexToColorARGB(String code, {Color fallBackColor}) {
LogUtils.d("hexToColor: input=$code");
if (TextUtils.isEmpty(code)) {
LogUtils.d("hexToColor: output=transparent");
return fallBackColor ?? Colors.transparent;
}
String trimmed = code.trim();
String tmp = trimmed.startsWith("#") ? trimmed.substring(1) : trimmed;
int length = tmp.length;
if (length != 3 && length != 6 && length != 8) {
LogUtils.d("hexToColor: output=transparent");
return fallBackColor ?? Colors.transparent;
}
int a = hexToA(tmp);
int r = hexToR(tmp);
int g = hexToG(tmp);
int b = hexToB(tmp);
LogUtils.d("hexToColor: output=ARGB[$a,$r,$g,$b]");
Color c = Color.fromARGB(a, r, g, b);
return c;
}
static int hexToA(String code) {
try {
int length = code.length;
if (length < 8) return 255;
return int.parse(code.substring(0, 2), radix: 16);
} catch (e) {
LogUtils.d("hexToA: $e");
return 0;
}
}
static int hexToR(String code) {
try {
int length = code.length;
if (length == 3) {
var s = code.substring(0, 1);
s += s;
return int.parse(s, radix: 16);
} else if (length == 6)
return int.parse(code.substring(0, 2), radix: 16);
else
return int.parse(code.substring(2, 4), radix: 16);
} catch (e) {
LogUtils.d("hexToR: $e");
return 0;
}
}
static int hexToG(String code) {
try {
int length = code.length;
if (length == 3) {
var s = code.substring(1, 2);
s += s;
return int.parse(s, radix: 16);
} else if (length == 6)
return int.parse(code.substring(2, 4), radix: 16);
else
return int.parse(code.substring(4, 6), radix: 16);
} catch (e) {
LogUtils.d("hexToG: $e");
return 0;
}
}
static int hexToB(String code) {
try {
int length = code.length;
if (length == 3) {
var s = code.substring(2, 3);
s += s;
return int.parse(s, radix: 16);
} else if (length == 6)
return int.parse(code.substring(4, 6), radix: 16);
else
return int.parse(code.substring(6), radix: 16);
} catch (e) {
LogUtils.d("hexToB: $e");
return 0;
}
}
}
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/date/data_formats.dart | Dart |
class DateFormats {
/// 一些常用格式参照。如果下面格式不够,你可以自定义
/// 格式要求
static final String FULL = 'yyyy-MM-dd HH:mm:ss';
static final String Y_M_D_H_M = 'yyyy-MM-dd HH:mm';
static final String Y_M_D = 'yyyy-MM-dd';
static final String Y_M = 'yyyy-MM';
static final String M_D = 'MM-dd';
static final String M_D_H_M = 'MM-dd HH:mm';
static final String H_M_S = 'HH:mm:ss';
static final String H_M = 'HH:mm';
static final String ZH_FULL = 'yyyy年MM月dd日 HH时mm分ss秒';
static final String ZH_Y_M_D_H_M = 'yyyy年MM月dd日 HH时mm分';
static final String ZH_Y_M_D = 'yyyy年MM月dd日';
static final String ZH_Y_M = 'yyyy年MM月';
static final String ZH_M_D = 'MM月dd日';
static final String ZH_M_D_H_M = 'MM月dd日 HH时mm分';
static final String ZH_H_M_S = 'HH时mm分ss秒';
static final String ZH_H_M = 'HH时mm分';
static const String PARAM_FULL = 'yyyy/MM/dd HH:mm:ss';
static const String PARAM_Y_M_D_H_M = 'yyyy/MM/dd HH:mm';
static const String PARAM_Y_M_D = "yyyy/MM/dd";
static const String PARAM_Y_M = 'yyyy/MM';
static final String PARAM_M_D = 'MM/dd';
static final String PARAM_M_D_H_M = 'MM/dd HH:mm';
} | yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/date/date_utils.dart | Dart |
import 'package:yc_flutter_utils/date/data_formats.dart';
/// 日期时间工具类
class DateUtils {
/// get DateTime By DateStr.
/// 将字符串时间转化为DateTime
static DateTime getDateTime(String dateStr, {bool isUtc}) {
DateTime dateTime = DateTime.tryParse(dateStr);
if (isUtc != null) {
if (isUtc) {
dateTime = dateTime?.toUtc();
} else {
dateTime = dateTime?.toLocal();
}
}
return dateTime;
}
/// get DateTime By Milliseconds.
/// 将毫秒时间转化为DateTime
static DateTime getDateTimeByMs(int ms, {bool isUtc = false}) {
return DateTime.fromMillisecondsSinceEpoch(ms, isUtc: isUtc);
}
/// get DateMilliseconds By DateStr.
/// 将字符串时间转化为毫秒值
static int getDateMsByTimeString(String dateStr, {bool isUtc}) {
DateTime dateTime = getDateTime(dateStr, isUtc: isUtc);
return dateTime.millisecondsSinceEpoch;
}
/// get Now Date Time.
/// 获取当前日期返回DateTime
static DateTime getNowDateTime() {
return DateTime.now();
}
/// get Now Date Milliseconds.
/// 获取当前毫秒值
static int getNowDateMs() {
return DateTime.now().millisecondsSinceEpoch;
}
/// get Now Date Str.(yyyy-MM-dd HH:mm:ss)
/// 获取现在日期字符串,默认是:yyyy-MM-dd HH:mm:ss
static String getNowDateString() {
return formatDate(DateTime.now());
}
/// 获取昨天日期返回DateTime
static DateTime getYesterday() {
var dateTime = new DateTime.fromMillisecondsSinceEpoch(
DateTime.now().millisecondsSinceEpoch - 24 * 60 * 60 * 1000);
return dateTime;
}
/// 获取当前日期返回DateTime(utc)
static DateTime getNowUtcDateTime() {
return DateTime.now().toUtc();
}
/// 获取当前日期,返回指定格式
static String getNowDateTimeFormat(String outFormat) {
var formatResult = formatDate(getNowDateTime(),format: outFormat);
return formatResult;
}
/// 获取当前日期,返回指定格式
static String getUtcDateTimeFormat(String outFormat) {
var formatResult = formatDate(getNowUtcDateTime(),format: outFormat);
return formatResult;
}
/// format date by milliseconds.
/// 格式化日期毫秒时间
static String formatDateMilliseconds(int ms, {bool isUtc = false, String format}) {
return formatDate(getDateTimeByMs(ms, isUtc: isUtc), format: format);
}
/// format date by date str.
/// 格式化日期字符串
static String formatDateString(String dateStr, {bool isUtc, String format}) {
return formatDate(getDateTime(dateStr, isUtc: isUtc), format: format);
}
/// format date by DateTime.
/// format 转换格式(已提供常用格式 DateFormats,可以自定义格式:'yyyy/MM/dd HH:mm:ss')
static String formatDate(DateTime dateTime, {String format}) {
if (dateTime == null) return '';
format = format ?? DateFormats.FULL;
if (format.contains('yy')) {
String year = dateTime.year.toString();
if (format.contains('yyyy')) {
format = format.replaceAll('yyyy', year);
} else {
format = format.replaceAll('yy', year.substring(year.length - 2, year.length));
}
}
format = _comFormat(dateTime.month, format, 'M', 'MM');
format = _comFormat(dateTime.day, format, 'd', 'dd');
format = _comFormat(dateTime.hour, format, 'H', 'HH');
format = _comFormat(dateTime.minute, format, 'm', 'mm');
format = _comFormat(dateTime.second, format, 's', 'ss');
format = _comFormat(dateTime.millisecond, format, 'S', 'SSS');
return format;
}
/// com format.
static String _comFormat(
int value, String format, String single, String full) {
if (format.contains(single)) {
if (format.contains(full)) {
format =
format.replaceAll(full, value < 10 ? '0$value' : value.toString());
} else {
format = format.replaceAll(single, value.toString());
}
}
return format;
}
/// get WeekDay.
/// 获取dateTime是星期几
static String getWeekday(DateTime dateTime,
{String languageCode = 'en', bool short = false}) {
if (dateTime == null) return "";
String weekday = "";
switch (dateTime.weekday) {
case 1:
weekday = languageCode == 'zh' ? '星期一' : 'Monday';
break;
case 2:
weekday = languageCode == 'zh' ? '星期二' : 'Tuesday';
break;
case 3:
weekday = languageCode == 'zh' ? '星期三' : 'Wednesday';
break;
case 4:
weekday = languageCode == 'zh' ? '星期四' : 'Thursday';
break;
case 5:
weekday = languageCode == 'zh' ? '星期五' : 'Friday';
break;
case 6:
weekday = languageCode == 'zh' ? '星期六' : 'Saturday';
break;
case 7:
weekday = languageCode == 'zh' ? '星期日' : 'Sunday';
break;
default:
break;
}
return languageCode == 'zh'
? (short ? weekday.replaceAll('星期', '周') : weekday)
: weekday.substring(0, short ? 3 : weekday.length);
}
/// get WeekDay By Milliseconds.
/// 获取毫秒值对应是星期几
static String getWeekdayByMilliseconds(int milliseconds,
{bool isUtc = false, String languageCode = 'en', bool short = false}) {
DateTime dateTime = getDateTimeByMs(milliseconds, isUtc: isUtc);
return getWeekday(dateTime, languageCode: languageCode, short: short);
}
/// get day of year.
/// 在今年的第几天.
static int getDayOfYear(DateTime dateTime) {
int year = dateTime.year;
int month = dateTime.month;
int days = dateTime.day;
for (int i = 1; i < month; i++) {
days = days + MONTH_DAY[i];
}
if (isLeapYearByYear(year) && month > 2) {
days = days + 1;
}
return days;
}
/// get day of year.
/// 在今年的第几天.
static int getDayOfYearByMilliseconds(int ms, {bool isUtc = false}) {
return getDayOfYear(DateTime.fromMillisecondsSinceEpoch(ms, isUtc: isUtc));
}
/// is today.
/// 根据时间戳判断是否是今天
static bool isToday(int milliseconds, {bool isUtc = false, int locMs}) {
if (milliseconds == null || milliseconds == 0) return false;
DateTime old =
DateTime.fromMillisecondsSinceEpoch(milliseconds, isUtc: isUtc);
DateTime now;
if (locMs != null) {
now = DateUtils.getDateTimeByMs(locMs);
} else {
now = isUtc ? DateTime.now().toUtc() : DateTime.now().toLocal();
}
return old.year == now.year && old.month == now.month && old.day == now.day;
}
/// is yesterday by dateTime.
/// 根据时间判断是否是昨天
static bool isYesterday(DateTime dateTime, DateTime locDateTime) {
if (yearIsEqual(dateTime, locDateTime)) {
int spDay = getDayOfYear(locDateTime) - getDayOfYear(dateTime);
return spDay == 1;
} else {
return ((locDateTime.year - dateTime.year == 1) &&
dateTime.month == 12 && locDateTime.month == 1 &&
dateTime.day == 31 && locDateTime.day == 1);
}
}
/// is yesterday by millis.
/// 是否是昨天.
static bool isYesterdayByMilliseconds(int ms, int locMs) {
return isYesterday(DateTime.fromMillisecondsSinceEpoch(ms),
DateTime.fromMillisecondsSinceEpoch(locMs));
}
/// is Week.
/// 根据时间戳判断是否是本周
static bool isWeek(int ms, {bool isUtc = false, int locMs}) {
if (ms == null || ms <= 0) {
return false;
}
DateTime _old = DateTime.fromMillisecondsSinceEpoch(ms, isUtc: isUtc);
DateTime _now;
if (locMs != null) {
_now = DateUtils.getDateTimeByMs(locMs, isUtc: isUtc);
} else {
_now = isUtc ? DateTime.now().toUtc() : DateTime.now().toLocal();
}
DateTime old =
_now.millisecondsSinceEpoch > _old.millisecondsSinceEpoch ? _old : _now;
DateTime now =
_now.millisecondsSinceEpoch > _old.millisecondsSinceEpoch ? _now : _old;
return (now.weekday >= old.weekday) &&
(now.millisecondsSinceEpoch - old.millisecondsSinceEpoch <=
7 * 24 * 60 * 60 * 1000);
}
/// year is equal.
/// 是否同年.
static bool yearIsEqual(DateTime dateTime, DateTime locDateTime) {
return dateTime.year == locDateTime.year;
}
/// year is equal.
/// 是否同年.
static bool yearIsEqualByMilliseconds(int ms, int locMs) {
return yearIsEqual(DateTime.fromMillisecondsSinceEpoch(ms),
DateTime.fromMillisecondsSinceEpoch(locMs));
}
/// Return whether it is leap year.
/// 是否是闰年
static bool isLeapYear(DateTime dateTime) {
return isLeapYearByYear(dateTime.year);
}
/// Return whether it is leap year.
/// 是否是闰年
static bool isLeapYearByMilliseconds(int milliseconds) {
var dateTime = getDateTimeByMs(milliseconds);
return isLeapYearByYear(dateTime.year);
}
/// Return whether it is leap year.
/// 是否是闰年
static bool isLeapYearByYear(int year) {
return year % 4 == 0 && year % 100 != 0 || year % 400 == 0;
}
///判断a和b两个时间是否是同一天
static bool isSameDay(DateTime a, DateTime b) {
return a.year == b.year && a.month == b.month && a.day == b.day;
}
/// Returns [DateTime] for the beginning of the day (00:00:00).
///
/// (2020, 4, 9, 16, 50) -> (2020, 4, 9, 0, 0)
static DateTime startOfDay(DateTime dateTime) =>
_date(dateTime.isUtc, dateTime.year, dateTime.month, dateTime.day);
/// Returns [DateTime] for the beginning of the next day (00:00:00).
///
/// (2020, 4, 9, 16, 50) -> (2020, 4, 10, 0, 0)
static DateTime startOfNextDay(DateTime dateTime) =>
_date(dateTime.isUtc, dateTime.year, dateTime.month, dateTime.day + 1);
/// Returns [DateTime] for the beginning of today (00:00:00).
static DateTime startOfToday() => startOfDay(DateTime.now());
/// Creates a copy of [date] but with time replaced with the new values.
static DateTime setTime(DateTime date, int hours, int minutes,
[int seconds = 0, int milliseconds = 0, int microseconds = 0]) =>
_date(date.isUtc, date.year, date.month, date.day, hours, minutes,
seconds, milliseconds, microseconds);
/// Creates a copy of [date] but with the given fields
/// replaced with the new values.
static DateTime copyWith(DateTime date,
{int year,
int month,
int day,
int hour,
int minute,
int second,
int millisecond,
int microsecond}) =>
_date(
date.isUtc,
year ?? date.year,
month ?? date.month,
day ?? date.day,
hour ?? date.hour,
minute ?? date.minute,
second ?? date.second,
millisecond ?? date.millisecond,
microsecond ?? date.microsecond);
/// Returns a number of the next month.
static int nextMonth(DateTime date) {
final month = date.month;
return month == DateTime.monthsPerYear ? 1 : month + 1;
}
/// Returns the [DateTime] resulting from adding the given number
/// of months to this [DateTime].
///
/// The result is computed by incrementing the month parts of this
/// [DateTime] by months months, and, if required, adjusting the day part
/// of the resulting date downwards to the last day of the resulting month.
///
/// For example:
/// (2020, 12, 31) -> add 2 months -> (2021, 2, 28).
/// (2020, 12, 31) -> add 1 month -> (2021, 1, 31).
static DateTime addMonths(DateTime date, int months) {
var res = DateUtils.copyWith(date, month: date.month + months);
if (date.day != res.day) res = DateUtils.copyWith(res, day: 0);
return res;
}
/// Returns week number in year.
///
/// The first week of the year is the week that contains
/// 4 or more days of that year (='First 4-day week').
///
/// So if week contains less than 4 days - it's in another year.
///
/// The highest week number in a year is either 52 or 53.
///
/// You can define first weekday (Monday, Sunday or Saturday) with
/// parameter [firstWeekday]. It should be one of the constant values
/// [DateTime.monday], ..., [DateTime.sunday].
///
/// By default it's [DateTime.monday].
static int getWeekNumber(DateTime date, {int firstWeekday}) {
assert(firstWeekday == null || firstWeekday > 0 && firstWeekday < 8);
if (isWeekInYear(date, date.year, firstWeekday)) {
final startOfTheFirstWeek =
firstDayOfFirstWeek(date.year, firstWeekday: firstWeekday);
final diffInDays = getDaysDifference(date, startOfTheFirstWeek);
return (diffInDays / DateTime.daysPerWeek).floor() + 1;
} else if (date.month == DateTime.december) {
// first of the next year
return 1;
} else {
// last of the previous year
return getWeekNumber(DateTime(date.year - 1, DateTime.december, 31),
firstWeekday: firstWeekday);
}
}
/// Returns number of the last week in [year].
///
/// You can define first weekday (Monday, Sunday or Saturday) with
/// parameter [firstWeekday]. It should be one of the constant values
/// [DateTime.monday], ..., [DateTime.sunday].
///
/// By default it's [DateTime.monday].
///
/// See [getWeekNumber].
static int getLastWeekNumber(int year, {int firstWeekday}) {
assert(firstWeekday == null || firstWeekday > 0 && firstWeekday < 8);
final start = firstDayOfFirstWeek(year, firstWeekday: firstWeekday);
final end = firstDayOfWeek(DateTime(year, DateTime.december, 31),
firstWeekday: firstWeekday);
final diffInDays = getDaysDifference(end, start);
var res = diffInDays ~/ DateTime.daysPerWeek;
if (isWeekInYear(end, year, firstWeekday)) res++;
return res;
}
/// Returns number of the day in week (starting with 1).
///
/// Difference from [DateTime.weekday] is that
/// you can define first weekday (Monday, Sunday or Saturday) with
/// parameter [firstWeekday]. It should be one of the constant values
/// [DateTime.monday], ..., [DateTime.sunday].
///
/// By default it's [DateTime.monday].
///
static int getDayNumberInWeek(DateTime date, {int firstWeekday}) {
var res = date.weekday - (firstWeekday ?? DateTime.monday) + 1;
if (res <= 0) res += DateTime.daysPerWeek;
return res;
}
/// Returns number of the day in year.
///
/// Starting with 1.
static int getDayNumberInYear(DateTime date) {
final firstDayOfYear = DateTime(date.year, DateTime.january, 1);
return getDaysDifference(date, firstDayOfYear) + 1;
}
/// Returns the number of days in a given year.
static int getDaysInYear(int year) {
final lastDayOfYear = DateTime(year, DateTime.december, 31);
return getDayNumberInYear(lastDayOfYear);
}
/// Returns count of days between two dates.
///
/// Time will be ignored, so for the dates
/// (2020, 11, 18, 16, 50) and (2020, 11, 19, 10, 00)
/// result will be 1.
///
/// Use this method for count days instead of
/// `a.difference(b).inDays`, since it can return
/// some unexpected result, because of daylight saving hour.
static int getDaysDifference(DateTime a, DateTime b) {
final straight = a.isBefore(b);
final start = startOfDay(straight ? a : b);
final end = startOfDay(straight ? b : a).add(const Duration(hours: 12));
final diff = end.difference(start);
return diff.inHours ~/ 24;
}
/// Checks if [day] is in the first day of a week.
///
/// You can define first weekday (Monday, Sunday or Saturday) with
/// parameter [firstWeekday]. It should be one of the constant values
/// [DateTime.monday], ..., [DateTime.sunday].
///
/// By default it's [DateTime.monday].
static bool isFirstDayOfWeek(DateTime day, {int firstWeekday}) {
assert(firstWeekday == null || firstWeekday > 0 && firstWeekday < 8);
return isSameDay(firstDayOfWeek(day, firstWeekday: firstWeekday), day);
}
/// Checks if [day] is in the last day of a week.
///
/// You can define first weekday (Monday, Sunday or Saturday) with
/// parameter [firstWeekday]. It should be one of the constant values
/// [DateTime.monday], ..., [DateTime.sunday].
///
/// By default it's [DateTime.monday],
/// so the last day will be [DateTime.sunday].
static bool isLastDayOfWeek(DateTime day, {int firstWeekday}) {
assert(firstWeekday == null || firstWeekday > 0 && firstWeekday < 8);
return isSameDay(lastDayOfWeek(day, firstWeekday: firstWeekday), day);
}
/// Checks if [day] is in the first day of a month.
static bool isFirstDayOfMonth(DateTime day) {
return day.day == 1;
}
/// Checks if [day] is in the last day of a month.
static bool isLastDayOfMonth(DateTime day) {
return nextDay(day).month != day.month;
}
/// Returns start of the first day of the week for specified [dateTime].
///
/// For example: (2020, 4, 9, 15, 16) -> (2020, 4, 6, 0, 0, 0, 0).
///
/// You can define first weekday (Monday, Sunday or Saturday) with
/// parameter [firstWeekday]. It should be one of the constant values
/// [DateTime.monday], ..., [DateTime.sunday].
///
/// By default it's [DateTime.monday].
static DateTime firstDayOfWeek(DateTime dateTime, {int firstWeekday}) {
assert(firstWeekday == null || firstWeekday > 0 && firstWeekday < 8);
var days = dateTime.weekday - (firstWeekday ?? DateTime.monday);
if (days < 0) days += DateTime.daysPerWeek;
return _date(
dateTime.isUtc, dateTime.year, dateTime.month, dateTime.day - days);
}
/// Returns start of the first day of the first week in [year].
///
/// For example: (2020, 4, 9, 15, 16) -> (2019, 12, 30, 0, 0, 0, 0).
///
/// You can define first weekday (Monday, Sunday or Saturday) with
/// parameter [firstWeekday]. It should be one of the constant values
/// [DateTime.monday], ..., [DateTime.sunday].
///
/// By default it's [DateTime.monday].
///
/// See [getWeekNumber].
static DateTime firstDayOfFirstWeek(int year, {int firstWeekday}) {
assert(firstWeekday == null || firstWeekday > 0 && firstWeekday < 8);
final startOfYear = DateTime(year);
return isWeekInYear(startOfYear, year, firstWeekday)
? firstDayOfWeek(startOfYear, firstWeekday: firstWeekday)
: firstDayOfNextWeek(startOfYear, firstWeekday: firstWeekday);
}
/// Returns start of the first day of the next week for specified [dateTime].
///
/// For example: (2020, 4, 9, 15, 16) -> (2020, 4, 13, 0, 0, 0, 0).
///
/// You can define first weekday (Monday, Sunday or Saturday) with
/// parameter [firstWeekday]. It should be one of the constant values
/// [DateTime.monday], ..., [DateTime.sunday].
/// By default it's [DateTime.monday].
static DateTime firstDayOfNextWeek(DateTime dateTime, {int firstWeekday}) {
assert(firstWeekday == null || firstWeekday > 0 && firstWeekday < 8);
var days = dateTime.weekday - (firstWeekday ?? DateTime.monday);
if (days >= 0) days -= DateTime.daysPerWeek;
return _date(
dateTime.isUtc, dateTime.year, dateTime.month, dateTime.day - days);
}
/// Returns start of the last day of the week for specified [dateTime].
///
/// For example: (2020, 4, 9, 15, 16) -> (2020, 4, 12, 0, 0, 0, 0).
///
/// You can define first weekday (Monday, Sunday or Saturday) with
/// parameter [firstWeekday]. It should be one of the constant values
/// [DateTime.monday], ..., [DateTime.sunday].
///
/// By default it's [DateTime.monday],
/// so the last day will be [DateTime.sunday].
static DateTime lastDayOfWeek(DateTime dateTime, {int firstWeekday}) {
assert(firstWeekday == null || firstWeekday > 0 && firstWeekday < 8);
var days = (firstWeekday ?? DateTime.monday) - 1 - dateTime.weekday;
if (days < 0) days += DateTime.daysPerWeek;
return _date(
dateTime.isUtc, dateTime.year, dateTime.month, dateTime.day + days);
}
/// Returns [DateTime] that represents a beginning
/// of the first day of the month containing [date].
///
/// Example: (2020, 4, 9, 15, 16) -> (2020, 4, 1, 0, 0, 0, 0).
static DateTime firstDayOfMonth(DateTime date) {
return _date(date.isUtc, date.year, date.month);
}
/// Returns [DateTime] that represents a beginning
/// of the first day of the next month.
///
/// Example: (2020, 4, 9, 15, 16) -> (2020, 5, 1, 0, 0, 0, 0).
static DateTime firstDayOfNextMonth(DateTime dateTime) {
final month = dateTime.month;
final year = dateTime.year;
final nextMonthStart = (month < DateTime.monthsPerYear)
? _date(dateTime.isUtc, year, month + 1, 1)
: _date(dateTime.isUtc, year + 1, 1, 1);
return nextMonthStart;
}
/// Returns [DateTime] that represents a beginning
/// of the last day of the month containing [date].
///
/// Example: (2020, 4, 9, 15, 16) -> (2020, 4, 30, 0, 0, 0, 0).
static DateTime lastDayOfMonth(DateTime dateTime) {
return previousDay(firstDayOfNextMonth(dateTime));
}
/// Returns [DateTime] that represents a beginning
/// of the first day of the year containing [date].
///
/// Example: (2020, 3, 9, 15, 16) -> (2020, 1, 1, 0, 0, 0, 0).
static DateTime firstDayOfYear(DateTime dateTime) {
return _date(dateTime.isUtc, dateTime.year, 1, 1);
}
/// Returns [DateTime] that represents a beginning
/// of the first day of the next year.
///
/// Example: (2020, 3, 9, 15, 16) -> (2021, 1, 1, 0, 0, 0, 0).
static DateTime firstDayOfNextYear(DateTime dateTime) {
return _date(dateTime.isUtc, dateTime.year + 1, 1, 1);
}
/// Returns [DateTime] that represents a beginning
/// of the last day of the year containing [date].
///
/// Example: (2020, 4, 9, 15, 16) -> (2020, 12, 31, 0, 0, 0, 0).
static DateTime lastDayOfYear(DateTime dateTime) {
return _date(dateTime.isUtc, dateTime.year, DateTime.december, 31);
}
/// Проверяет является ли заданная дата текущей.
static bool isCurrentDate(DateTime date) {
final now = DateTime.now();
return isSameDay(date, now);
}
/// Returns number of days in the [month] of the [year].
static int getDaysInMonth(int year, int monthNum) {
assert(monthNum > 0);
assert(monthNum <= 12);
return DateTime(year, monthNum + 1, 0).day;
}
/// Returns same time in the next day.
static DateTime nextDay(DateTime d) {
return copyWith(d, day: d.day + 1);
}
/// Returns same time in the previous day.
static DateTime previousDay(DateTime d) {
return copyWith(d, day: d.day - 1);
}
/// Returns same date in the next year.
static DateTime nextYear(DateTime d) {
return _date(d.isUtc, d.year + 1, d.month, d.day);
}
/// Returns same date in the previous year.
static DateTime previousYear(DateTime d) {
return _date(d.isUtc, d.year - 1, d.month, d.day);
}
/// Returns an iterable of [DateTime] with 1 day step in given range.
///
/// [start] is the start of the rande, inclusive.
/// [end] is the end of the range, exclusive.
///
/// If [start] equals [end], than [start] still will be included in interbale.
/// If [start] less than [end], than empty interable will be returned.
///
/// [DateTime] in result uses [start] timezone.
static Iterable<DateTime> generateWithDayStep(
DateTime start, DateTime end) sync* {
if (end.isBefore(start)) return;
var date = start;
do {
yield date;
date = nextDay(date);
} while (date.isBefore(end));
}
/// Checks if week, that contains [date] is in [year].
static bool isWeekInYear(DateTime date, int year, int firstWeekday) {
const requiredDaysInYear = 4;
final startWeekDate = firstDayOfWeek(date, firstWeekday: firstWeekday);
final endWeekDate = lastDayOfWeek(date, firstWeekday: firstWeekday);
if (startWeekDate.year == year && endWeekDate.year == year) {
return true;
} else if (endWeekDate.year == year) {
final startYearDate = DateTime(year, DateTime.january, 1);
final daysInPrevYear = getDaysDifference(startYearDate, startWeekDate);
return daysInPrevYear < requiredDaysInYear;
} else if (startWeekDate.year == year) {
final startNextYearDate = DateTime(year + 1, DateTime.january, 1);
final daysInNextYear =
getDaysDifference(endWeekDate, startNextYearDate) + 1;
return daysInNextYear < requiredDaysInYear;
} else {
return false;
}
}
static DateTime _date(bool utc, int year,
[int month = 1,
int day = 1,
int hour = 0,
int minute = 0,
int second = 0,
int millisecond = 0,
int microsecond = 0]) =>
utc
? DateTime.utc(
year, month, day, hour, minute, second, millisecond, microsecond)
: DateTime(
year, month, day, hour, minute, second, millisecond, microsecond);
}
/// month->days.
Map<int, int> MONTH_DAY = {
1: 31,
2: 28,
3: 31,
4: 30,
5: 31,
6: 30,
7: 31,
8: 31,
9: 30,
10: 31,
11: 30,
12: 31,
}; | yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/encrypt/encrypt_utils.dart | Dart | import 'dart:convert';
import 'dart:io';
import 'package:crypto/crypto.dart';
import 'package:convert/convert.dart';
/// 加密和解密工具类
class EncryptUtils {
/// md5 加密字符串
static String encodeMd5(String data) {
var content = Utf8Encoder().convert(data);
var digest = md5.convert(content);
return hex.encode(digest.bytes);
}
/// md5 加密file
static String encodeMd5File(File file) {
var readAsStringSync = file.readAsStringSync();
var content = Utf8Encoder().convert(readAsStringSync);
var digest = md5.convert(content);
return hex.encode(digest.bytes);
}
/// 异或对称加密
static String xorCode(String res, String key) {
List<String> keyList = key.split(',');
List<int> codeUnits = res.codeUnits;
List<int> codes = [];
for (int i = 0, length = codeUnits.length; i < length; i++) {
int code = codeUnits[i] ^ int.parse(keyList[i % keyList.length]);
codes.add(code);
}
return String.fromCharCodes(codes);
}
/// 异或对称 Base64 加密
static String xorBase64Encode(String res, String key) {
String encode = xorCode(res, key);
encode = encodeBase64(encode);
return encode;
}
/// 异或对称 Base64 解密
static String xorBase64Decode(String res, String key) {
String encode = decodeBase64(res);
encode = xorCode(encode, key);
return encode;
}
/// Base64加密字符串
static String encodeBase64(String data) {
var content = utf8.encode(data);
var digest = base64Encode(content);
return digest;
}
/// Base64解密字符串
static String decodeBase64(String data) {
List<int> bytes = base64Decode(data);
String result = utf8.decode(bytes);
return result;
}
}
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/except/handle_exception.dart | Dart | import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:yc_flutter_utils/log/log_utils.dart';
const bool _inProduction = const bool.fromEnvironment("dart.vm.product");
const String TAG = "handle_exception : ";
void _reportError(dynamic e, StackTrace stack) {
LogUtils.e('$TAG e---->' + e.toString());
LogUtils.e('$TAG stack---->' + stack.toString());
}
String _stringify(Object exception) {
try {
return exception.toString();
} catch (e) {
// intentionally left empty.
}
return 'Error';
}
Widget _errorWidgetBuilder(FlutterErrorDetails details) {
LogUtils.e('$TAG _errorWidgetBuilder '+ _stringify(details.exception)
+ _stringify(details.stack));
String message = '';
if (true) {
message = _stringify(details.exception) +
'\nSee also: https://flutter.dev/docs/testing/errors';
}
final Object exception = details.exception;
return ErrorWidget.withDetails(
message: message, error: exception is FlutterError ? exception : null);
}
void hookCrash(Function main) {
ErrorWidget.builder =
(FlutterErrorDetails errorDetails) => _errorWidgetBuilder(errorDetails);
if (_inProduction) {
FlutterError.onError = (FlutterErrorDetails details) async {
Zone.current.handleUncaughtError(details.exception, details.stack);
};
}
runZoned<Future<void>>(() async {
LogUtils.d('$TAG runZoned');
main();
LogUtils.d('$TAG runZoned main');
},
onError: (dynamic error, StackTrace stack) {
//捕获异常打印日志
_reportError(error, stack);
},
);
}
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/extens/extension_int.dart | Dart |
import 'package:yc_flutter_utils/extens/transform_utils.dart';
import 'package:yc_flutter_utils/extens/validator_utils.dart';
import 'package:yc_flutter_utils/object/object_utils.dart';
/// Num扩展也适用于int
extension ExtensionInt on int {
/// Checks if int value is Palindrome.
/// 检查int是否为回文
bool isPalindrome() {
var numericOnly = TransformUtils.numericOnly(this.toString());
return ValidatorUtils.isPalindrome(numericOnly);
}
/// Checks if all int value are same.
/// 检查所有数据是否具有相同的值
/// Example: 111111 -> true
bool isOneAKind() => ValidatorUtils.isOneAKind(this);
/// Transform int value to binary string
/// 转换int值为二进制
String toBinary() => TransformUtils.toBinary(this);
/// Transform int value to binary int
/// 转换int值为二进制int
int toBinaryInt() => int.parse(TransformUtils.toBinary(this));
/// Transform int value to binary string
/// 转换int值为二进制字符串
/// Example: 1111 => 15
int fromBinary() => TransformUtils.fromBinary(this.toString());
}
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/extens/extension_list.dart | Dart |
import 'dart:convert';
import 'package:yc_flutter_utils/extens/validator_utils.dart';
import 'package:yc_flutter_utils/object/object_utils.dart';
extension ExtensionList on List {
/// Transform list to json
/// 将list转化为json字符串
String toJsonString() {
return jsonEncode(this);
}
/// 将list转化为json字符串,换行
String getJsonPretty() {
return JsonEncoder.withIndent('\t').convert(this);
}
/// Get total value of list of num (int/double)
/// 获取num列表的总值(int/double)
/// Example: [1,2,3,4] => 10
num valueTotal() {
num total = 0;
if (this == null || this.isEmpty) return total;
if (this[0] is num) for (var v in this) total += v;
throw FormatException('Can only accepting list of num (int/double)');
}
/// Checks if data is null.
/// 判断对象是否为null
bool isNull() => ObjectUtils.isNull(this);
/// Checks if data is null or Blank (Empty or only contains whitespace).
/// 检查数据是否为空或空(空或只包含空格)
bool isNullOrBlank() => ObjectUtils.isNullOrBlank(this);
/// Checks if length of list is LOWER OR EQUAL to maxLength.
/// 检查数据长度是否小于或等于maxLength
bool isLengthLowerOrEqual(int maxLength) =>
ValidatorUtils.isLengthLowerOrEqual(this, maxLength);
/// Checks if length of list is GREATER than maxLength.
/// 检查数据长度是否大于maxLength
bool isLengthGreaterThan(int maxLength) =>
ValidatorUtils.isLengthGreaterThan(this, maxLength);
/// Checks if length of list is GREATER OR EQUAL to maxLength.
/// 检查数据长度是否大于或等于maxLength
bool isLengthGreaterOrEqual(int maxLength) =>
ValidatorUtils.isLengthGreaterOrEqual(this, maxLength);
/// Checks if length of list is EQUAL than maxLength.
/// 检查数据长度是否等于maxLength
bool isLengthEqualTo(int maxLength) =>
ValidatorUtils.isLengthEqualTo(this, maxLength);
/// Checks if length of list is BETWEEN minLength to maxLength.
/// 检查数据长度是否在minLength到maxLength之间
bool isLengthBetween(int minLength, int maxLength) =>
ValidatorUtils.isLengthBetween(this, minLength, maxLength);
}
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/extens/extension_map.dart | Dart |
import 'dart:convert';
import 'package:yc_flutter_utils/extens/validator_utils.dart';
import 'package:yc_flutter_utils/object/object_utils.dart';
extension ExtensionMap on Map {
/// Transform map to json
/// 将map转化为json字符串
String toJsonString() {
return jsonEncode(this);
}
/// 将map转化为json字符串换行
String getJsonPretty() {
return JsonEncoder.withIndent('\t').convert(this);
}
/// Checks if data is null.
/// 检查数据是否为空或空
bool isNull() => ObjectUtils.isNull(this);
/// Checks if data is null or Blank (Empty or only contains whitespace).
/// 检查数据是否为空或空
bool isNullOrBlank() => ObjectUtils.isNullOrBlank(this);
/// Checks if length of map is LOWER than maxLength.
/// 检查数据长度是否小于maxLength
bool isLengthLowerThan(int maxLength) =>
ValidatorUtils.isLengthLowerThan(this, maxLength);
/// Checks if length of map is LOWER OR EQUAL to maxLength.
bool isLengthLowerOrEqual(int maxLength) =>
ValidatorUtils.isLengthLowerOrEqual(this, maxLength);
/// Checks if length of map is GREATER than maxLength.
bool isLengthGreaterThan(int maxLength) =>
ValidatorUtils.isLengthGreaterThan(this, maxLength);
/// Checks if length of map is GREATER OR EQUAL to maxLength.
bool isLengthGreaterOrEqual(int maxLength) =>
ValidatorUtils.isLengthGreaterOrEqual(this, maxLength);
/// Checks if length of map is EQUAL than maxLength.
bool isLengthEqualTo(int maxLength) =>
ValidatorUtils.isLengthEqualTo(this, maxLength);
/// Checks if length of map is BETWEEN minLength to maxLength.
bool isLengthBetween(int minLength, int maxLength) =>
ValidatorUtils.isLengthBetween(this, minLength, maxLength);
}
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/extens/extension_num.dart | Dart |
import 'package:yc_flutter_utils/extens/validator_utils.dart';
import 'package:yc_flutter_utils/object/object_utils.dart';
extension ExtensionNum on num {
/// Checks if data is null.
bool isNull() => ObjectUtils.isNull(this);
/// Checks if data is null or Blank (Empty or only contains whitespace).
bool isNullOrBlank() => ObjectUtils.isNullOrBlank(this);
/// Checks if num data is LOWER than comparedTo.
bool isLowerThan(num compareTo) => this < compareTo;
/// Checks if num data is GREATER than comparedTo.
bool isGreaterThan(num compareTo) => this > compareTo;
/// Checks if num data is EQUAL to compared one.
bool isEqualTo(num compareTo) => this == compareTo;
/// Checks if length of num is LOWER than maxLength.
bool isLengthLowerThan(int maxLength) =>
ValidatorUtils.isLengthLowerThan(this, maxLength);
/// Checks if length of num is LOWER OR EQUAL to maxLength.
bool isLengthLowerOrEqual(int maxLength) =>
ValidatorUtils.isLengthLowerOrEqual(this, maxLength);
/// Checks if length of num is GREATER than maxLength.
bool isLengthGreaterThan(int maxLength) =>
ValidatorUtils.isLengthGreaterThan(this, maxLength);
/// Checks if length of num is GREATER OR EQUAL to maxLength.
bool isLengthGreaterOrEqual(int maxLength) =>
ValidatorUtils.isLengthGreaterOrEqual(this, maxLength);
/// Checks if length of num is EQUAL than maxLength.
bool isLengthEqualTo(int maxLength) =>
ValidatorUtils.isLengthEqualTo(this, maxLength);
/// Checks if length of num is BETWEEN minLength to maxLength.
bool isLengthBetween(int minLength, int maxLength) =>
ValidatorUtils.isLengthBetween(this, minLength, maxLength);
}
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/extens/extension_set.dart | Dart |
import 'package:yc_flutter_utils/extens/validator_utils.dart';
import 'package:yc_flutter_utils/object/object_utils.dart';
extension ExtensionSet on Set {
/// Checks if data is null.
bool isNull() => ObjectUtils.isNull(this);
/// Checks if data is null or Blank (Empty or only contains whitespace).
bool isNullOrBlank() => ObjectUtils.isNullOrBlank(this);
/// Checks if length of set is LOWER than maxLength.
bool isLengthLowerThan(int maxLength) =>
ValidatorUtils.isLengthLowerThan(this, maxLength);
/// Checks if length of set is LOWER OR EQUAL to maxLength.
bool isLengthLowerOrEqual(int maxLength) =>
ValidatorUtils.isLengthLowerOrEqual(this, maxLength);
/// Checks if length of set is GREATER than maxLength.
bool isLengthGreaterThan(int maxLength) =>
ValidatorUtils.isLengthGreaterThan(this, maxLength);
/// Checks if length of set is GREATER OR EQUAL to maxLength.
bool isLengthGreaterOrEqual(int maxLength) =>
ValidatorUtils.isLengthGreaterOrEqual(this, maxLength);
/// Checks if length of set is EQUAL than maxLength.
bool isLengthEqualTo(int maxLength) =>
ValidatorUtils.isLengthEqualTo(this, maxLength);
/// Checks if length of set is BETWEEN minLength to maxLength.
bool isLengthBetween(int minLength, int maxLength) =>
ValidatorUtils.isLengthBetween(this, minLength, maxLength);
}
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/extens/extension_string.dart | Dart |
import 'package:yc_flutter_utils/extens/transform_utils.dart';
import 'package:yc_flutter_utils/extens/validator_utils.dart';
import 'package:yc_flutter_utils/num/num_utils.dart';
import 'package:yc_flutter_utils/object/object_utils.dart';
extension ExtensionString on String {
/// Checks if data is null.
bool isNull() => ObjectUtils.isNull(this);
/// Checks if data is null or Blank (empty or only contains whitespace).
bool isNullOrBlank() => ObjectUtils.isNullOrBlank(this);
/// Checks if string is num (int or double).
bool isNum() => NumUtils.isNum(this);
/// Checks if string is numeric only.
/// Numeric only doesnt accepting "." which double data type have
bool isNumericOnly() => ValidatorUtils.isNumericOnly(this);
/// Checks if string consist only Alphabet. (No Whitespace)
bool isAlphabetOnly(String s) => ValidatorUtils.isAlphabetOnly(s);
/// Checks if string is boolean.
bool isBool() => ValidatorUtils.isBool(this);
/// Checks if string is vector image file path.
bool isVector() => ValidatorUtils.isVector(this);
/// Checks if string is image file path.
bool isImage() => ValidatorUtils.isImage(this);
/// Checks if string is audio file path.
bool isAudio() => ValidatorUtils.isAudio(this);
/// Checks if string is video file path.
bool isVideo() => ValidatorUtils.isVideo(this);
/// Checks if string is txt file path.
bool isTxt() => ValidatorUtils.isTxt(this);
/// Checks if string is Doc file path.
bool isDocument() => ValidatorUtils.isDocument(this);
/// Checks if string is Excel file path.
bool isExcel() => ValidatorUtils.isExcel(this);
/// Checks if string is powerpoint file path.
bool isPPT() => ValidatorUtils.isPPT(this);
/// Checks if string is APK file path.
bool isApk() => ValidatorUtils.isAPK(this);
/// Checks if string is PDF file path.
bool isPDF() => ValidatorUtils.isPDF(this);
/// Checks if string is html file path.
bool isHTML() => ValidatorUtils.isHTML(this);
/// Checks if string is URL.
bool isURL() => ValidatorUtils.isURL(this);
/// Checks if string is DateTime (UTC or Iso8601).
bool isDateTime() => ValidatorUtils.isDateTime(this);
/// Checks if string is email.
bool isEmail({int minLength, int maxLength}) =>
ValidatorUtils.isEmail(this) &&
((minLength != null)
? ValidatorUtils.isLengthGreaterOrEqual(this, minLength)
: true) &&
((maxLength != null)
? ValidatorUtils.isLengthLowerOrEqual(this, maxLength)
: true);
/// Checks if string is MD5
bool isMD5() => ValidatorUtils.isMD5(this);
/// Checks if string is SHA251.
bool isSHA1() => ValidatorUtils.isSHA1(this);
/// Checks if string is SHA256.
bool isSHA256() => ValidatorUtils.isSHA256(this);
/// Checks if string is Palindrom.
bool isPalindrom() => ValidatorUtils.isPalindrome(this);
/// Checks if all character inside string are same.
/// Example: 111111 -> true, wwwww -> true
bool isOneAKind() => ValidatorUtils.isOneAKind(this);
/// Checks if string is IPv4.
bool isIPv4() => ValidatorUtils.isIPv4(this);
/// Checks if string is IPv6.
bool isIPv6() => ValidatorUtils.isIPv6(this);
/// Checks if length of string is LOWER than maxLength.
bool isLengthLowerThan(int maxLength) =>
ValidatorUtils.isLengthLowerThan(this, maxLength);
/// Checks if length of string is LOWER OR EQUAL to maxLength.
bool isLengthLowerOrEqual(int maxLength) =>
ValidatorUtils.isLengthLowerOrEqual(this, maxLength);
/// Checks if length of string is GREATER than maxLength.
bool isLengthGreaterThan(int maxLength) =>
ValidatorUtils.isLengthGreaterThan(this, maxLength);
/// Checks if length of string is GREATER OR EQUAL to maxLength.
bool isLengthGreaterOrEqual(int maxLength) =>
ValidatorUtils.isLengthGreaterOrEqual(this, maxLength);
/// Checks if length of string is EQUAL than maxLength.
bool isLengthEqualTo(int maxLength) =>
ValidatorUtils.isLengthEqualTo(this, maxLength);
/// Checks if length of string is BETWEEN minLength to maxLength.
bool isLengthBetween(int minLength, int maxLength) =>
ValidatorUtils.isLengthBetween(this, minLength, maxLength);
/// Checks if a contains b (Treating or interpreting upper- and lowercase letters as being the same).
bool isCaseInsensitiveContains(String compareTo) =>
ValidatorUtils.isCaseInsensitiveContains(this, compareTo);
/// Checks if a contains b or b contains a (Treating or interpreting upper- and lowercase letters as being the same).
bool isCaseInsensitiveContainsAny(String compareTo) =>
ValidatorUtils.isCaseInsensitiveContainsAny(this, compareTo);
/// Checks if string value is camelcase.
bool isCamelCase() => ValidatorUtils.isCamelCase(this);
/// Checks if string value is capitalize.
bool isCapitalize({bool firstOnly = false}) =>
ValidatorUtils.isCapitalize(this, firstOnly: firstOnly);
/// Transform string to int type
int toInt({bool nullOnError = false}) {
int i = int.tryParse(this);
if (i != null) return i;
if (nullOnError) return null;
throw FormatException('Can only acception double value');
}
/// Transform string to double type
double toDouble({bool nullOnError = false}) {
double d = double.tryParse(this);
if (d != null) return d;
if (nullOnError) return null;
throw FormatException('Can only acception double value');
}
/// Transform string to num type
num toNum({bool nullOnError = false}) =>
nullOnError ? num.tryParse(this) : num.parse(this);
/// Transform string to boolean type
bool toBool({bool falseOnError = false}) {
if (ValidatorUtils.isBool(this)) return this == 'true';
if (falseOnError) return false;
throw FormatException('Can only acception boolean value');
}
/// Transform String millisecondsSinceEpoch (DateTime) to DateTime
DateTime toDateTime() {
int miliseconds = this.toInt(nullOnError: true);
if (ObjectUtils.isNullOrBlank(miliseconds)) return null;
return DateTime.fromMillisecondsSinceEpoch(miliseconds);
}
/// Transform string value to binary
/// Example: 15 => 1111
String toBinary({bool nullOnError = false}) {
if (!NumUtils.isNum(this)) {
if (nullOnError) return null;
throw FormatException("Only accepting integer value");
}
return TransformUtils.toBinary(int.parse(this));
}
/// Capitalize each word inside string
/// Example: your name => Your Name, your name => Your name
///
/// If First Only is `true`, the only letter get uppercase is the first letter
String toCapitalize({bool firstOnly = false}) =>
TransformUtils.capitalize(this, firstOnly: firstOnly);
/// Capitalize each word inside string
/// Example: your name => yourName
String toCamelCase() => TransformUtils.camelCase(this);
/// Extract numeric value of string
/// Example: OTP 12312 27/04/2020 => 1231227042020ß
/// If firstword only is true, then the example return is "12312" (first found numeric word)
String toNumericOnly() => TransformUtils.numericOnly(this);
}
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/extens/transform_utils.dart | Dart |
import 'package:yc_flutter_utils/extens/validator_utils.dart';
import 'package:yc_flutter_utils/num/num_utils.dart';
import 'package:yc_flutter_utils/object/object_utils.dart';
/// 转化工具类
class TransformUtils {
/// Transform int value to binary
/// 转换int值为二进制
/// Example: 15 => 1111
static String toBinary(int i) => i.toRadixString(2);
/// Transform int value to binary
/// 转换int值为二进制
/// Example: 15 => 1111
static int toBinaryInt(int i) => int.parse(i.toRadixString(2));
/// Transform binary to int value
/// 转换二进制为int值
/// Example: 1111 => 15
static int fromBinary(String binaryStr) => int.tryParse(binaryStr, radix: 2);
/// Capitalize each word inside string
/// 字符串内的每个单词都要大写
/// Example: your name => Your Name, your name => Your name
/// If First Only is `true`, the only letter get uppercase is the first letter
static String capitalize(String s, {bool firstOnly = false}) {
if (ObjectUtils.isNullOrBlank(s)) return null;
if (firstOnly) return capitalizeFirst(s);
List lst = s.split(' ');
String newStr = '';
for (var s in lst) newStr += capitalizeFirst(s);
return newStr;
}
/// Uppercase first letter inside string and let the others lowercase
/// 字符串的首字母大写,其他字母小写
/// Example: your name => Your name
static String capitalizeFirst(String s) {
if (ObjectUtils.isNullOrBlank(s)) return null;
return s[0].toUpperCase() + s.substring(1).toLowerCase();
}
/// Remove all whitespace inside string
/// 删除字符串内的所有空格
/// Example: your name => yourname
static String removeAllWhitespace(String s) {
if (ObjectUtils.isNullOrBlank(s)) {
return null;
}
return s.replaceAll(' ', '');
}
/// Camelcase string
/// Example: your name => yourName
static String camelCase(String s) {
if (ObjectUtils.isNullOrBlank(s)) {
return null;
}
return s[0].toLowerCase() + removeAllWhitespace(capitalize(s)).substring(1);
}
/// Extract numeric value of string
/// 提取字符串的数值
/// Example: OTP 12312 27/04/2020 => 1231227042020ß
/// If firstword only is true, then the example return is "12312" (first found numeric word)
static String numericOnly(String s, {bool firstWordOnly = false}) {
String numericOnlyStr = '';
for (var i = 0; i < s.length; i++) {
if (ValidatorUtils.isNumericOnly(s[i])) numericOnlyStr += s[i];
if (firstWordOnly && numericOnlyStr.isNotEmpty && s[i] == " ") break;
}
return numericOnlyStr;
}
}
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/extens/validator_utils.dart | Dart |
import 'package:yc_flutter_utils/extens/transform_utils.dart';
import 'package:yc_flutter_utils/object/object_utils.dart';
import 'package:yc_flutter_utils/regex/regex_constants.dart';
import 'package:yc_flutter_utils/regex/regex_utils.dart';
/// 验证器工具类
class ValidatorUtils {
/// 检查字符串是否只包含数字
/// 只有数值不接受double数据类型的
static bool isNumericOnly(String s) =>
RegexUtils.hasMatch(s, RegexConstants.numericOnly);
/// 检查字符串是否只包含字母。(没有空格)
static bool isAlphabetOnly(String s) =>
RegexUtils.hasMatch(s, RegexConstants.alphabetOnly);
/// 检查字符串是否为布尔值
static bool isBool(String s) {
if (ObjectUtils.isNull(s)) {
return false;
}
return (s == 'true' || s == 'false');
}
/// 检查string是否为vector文件
static bool isVector(String s) =>
RegexUtils.hasMatch(s, RegexConstants.vector);
/// Checks if string is an image file.
/// 检查字符串是否为图像文件
static bool isImage(String s) =>
RegexUtils.hasMatch(s, RegexConstants.image);
/// Checks if string is an audio file.
/// 检查字符串是否为音频文件
static bool isAudio(String s) =>
RegexUtils.hasMatch(s, RegexConstants.audio);
/// Checks if string is an video file.
/// 检查字符串是否为视频文件
static bool isVideo(String s) =>
RegexUtils.hasMatch(s, RegexConstants.video);
/// Checks if string is an txt file.
/// 检查字符串是否为txt文本文件
static bool isTxt(String s) =>
RegexUtils.hasMatch(s, RegexConstants.txt);
/// Checks if string is an Doc file.
/// 检查字符串是否为doc文件
static bool isDocument(String s) =>
RegexUtils.hasMatch(s, RegexConstants.doc);
/// Checks if string is an Excel file.
/// 检查字符串是否为excel文件
static bool isExcel(String s) =>
RegexUtils.hasMatch(s, RegexConstants.excel);
/// Checks if string is an PPT file.
/// 检查字符串是否为ppt文件
static bool isPPT(String s) =>
RegexUtils.hasMatch(s, RegexConstants.ppt);
/// Checks if string is an APK file.
/// 检查字符串是否为apk文件
static bool isAPK(String s) =>
RegexUtils.hasMatch(s, RegexConstants.apk);
/// Checks if string is an pdf file.
/// 检查字符串是否为pdf文件
static bool isPDF(String s) =>
RegexUtils.hasMatch(s, RegexConstants.pdf);
/// Checks if string is an HTML file.
/// 检查字符串是否为html文件
static bool isHTML(String s) =>
RegexUtils.hasMatch(s, RegexConstants.html);
/// Checks if string is URL.
/// 检查字符串是否为url文件
static bool isURL(String s) =>
RegexUtils.hasMatch(s, RegexConstants.url);
/// Checks if string is email.
/// 检查字符串是否为email文件
static bool isEmail(String s) =>
RegexUtils.hasMatch(s, RegexConstants.email);
/// Checks if string is DateTime (UTC or Iso8601).
/// 检查字符串是否为时间
static bool isDateTime(String s) =>
RegexUtils.hasMatch(s, RegexConstants.basicDateTime);
/// Checks if string is MD5 hash.
/// 检查字符串是否为md5
static bool isMD5(String s) =>
RegexUtils.hasMatch(s, RegexConstants.md5);
/// Checks if string is SHA1 hash.
/// 检查字符串是否为sha1
static bool isSHA1(String s) =>
RegexUtils.hasMatch(s, RegexConstants.sha1);
/// Checks if string is SHA256 hash.
/// 检查字符串是否为sha256
static bool isSHA256(String s) =>
RegexUtils.hasMatch(s, RegexConstants.sha256);
/// Checks if string is IPv4.
/// 检查字符串是否为ipv4
static bool isIPv4(String s) =>
RegexUtils.hasMatch(s, RegexConstants.ipv4);
/// Checks if string is IPv6.
/// 检查字符串是否为ipv6
static bool isIPv6(String s) =>
RegexUtils.hasMatch(s, RegexConstants.ipv6);
/// Checks if string is Palindrome.
/// 检查字符串是否为回文
static bool isPalindrome(String s) {
bool isPalindrome = true;
for (var i = 0; i < s.length; i++) {
if (s[i] != s[s.length - i - 1]){
isPalindrome = false;
}
}
return isPalindrome;
}
/// Checks if all data have same value.
/// 检查所有数据是否具有相同的值
/// Example: 111111 -> true, wwwww -> true, [1,1,1,1] -> true
static bool isOneAKind(dynamic s) {
if ((s is String || s is List) && !ObjectUtils.isNullOrBlank(s)) {
var first = s[0];
var isOneAKind = true;
for (var i = 0; i < s.length; i++) {
if (s[i] != first) isOneAKind = false;
}
return isOneAKind;
}
if (s is int) {
String value = s.toString();
var first = value[0];
var isOneAKind = true;
for (var i = 0; i < value.length; i++) {
if (value[i] != first) isOneAKind = false;
}
return isOneAKind;
}
return false;
}
/// Checks if length of data is LOWER than maxLength.
/// 检查数据长度是否小于maxLength
static bool isLengthLowerThan(dynamic s, int maxLength) {
if (ObjectUtils.isNull(s)) return (maxLength <= 0) ? true : false;
switch (s.runtimeType) {
case String:
case List:
case Map:
case Set:
case Iterable:
return s.length < maxLength;
break;
case int:
return s.toString().length < maxLength;
break;
case double:
return s.toString().replaceAll('.', '').length < maxLength;
break;
default:
return false;
}
}
/// Checks if length of data is GREATER than maxLength.
/// 检查数据长度是否大于maxLength
static bool isLengthGreaterThan(dynamic s, int maxLength) {
if (ObjectUtils.isNull(s)) return false;
switch (s.runtimeType) {
case String:
case List:
case Map:
case Set:
case Iterable:
return s.length > maxLength;
break;
case int:
return s.toString().length > maxLength;
break;
case double:
return s.toString().replaceAll('.', '').length > maxLength;
break;
default:
return false;
}
}
/// Checks if length of data is GREATER OR EQUAL to maxLength.
/// 检查数据长度是否大于或等于maxLength。
static bool isLengthGreaterOrEqual(dynamic s, int maxLength) {
if (ObjectUtils.isNull(s)) return false;
switch (s.runtimeType) {
case String:
case List:
case Map:
case Set:
case Iterable:
return s.length >= maxLength;
break;
case int:
return s.toString().length >= maxLength;
break;
case double:
return s.toString().replaceAll('.', '').length >= maxLength;
break;
default:
return false;
}
}
/// Checks if length of data is LOWER OR EQUAL to maxLength.
/// 检查数据长度是否小于或等于maxLength
static bool isLengthLowerOrEqual(dynamic s, int maxLength) {
if (ObjectUtils.isNull(s)) return false;
switch (s.runtimeType) {
case String:
case List:
case Map:
case Set:
case Iterable:
return s.length <= maxLength;
break;
case int:
return s.toString().length <= maxLength;
break;
case double:
return s.toString().replaceAll('.', '').length <= maxLength;
default:
return false;
}
}
/// Checks if length of data is EQUAL to maxLength.
/// 检查数据长度是否等于maxLength。
static bool isLengthEqualTo(dynamic s, int maxLength) {
if (ObjectUtils.isNull(s)) return false;
switch (s.runtimeType) {
case String:
case List:
case Map:
case Set:
case Iterable:
return s.length == maxLength;
break;
case int:
return s.toString().length == maxLength;
break;
case double:
return s.toString().replaceAll('.', '').length == maxLength;
break;
default:
return false;
}
}
/// Checks if length of data is BETWEEN minLength to maxLength.
/// 检查数据长度是否在minLength到maxLength之间。
static bool isLengthBetween(dynamic s, int minLength, int maxLength) {
if (ObjectUtils.isNull(s)) {
return false;
}
return isLengthGreaterOrEqual(s, minLength) &&
isLengthLowerOrEqual(s, maxLength);
}
/// Checks if a contains b (Treating or interpreting upper- and lowercase letters as being the same).
/// 检查a是否包含b(将大小写字母视为相同或解释)。
static bool isCaseInsensitiveContains(String a, String b) =>
a.toLowerCase().contains(b.toLowerCase());
/// Checks if a contains b or b contains a (Treating or interpreting upper- and lowercase letters as being the same).
/// 检查a中是否包含b或b中是否包含a(将大小写字母视为相同)。
static bool isCaseInsensitiveContainsAny(String a, String b) {
String lowA = a.toLowerCase();
String lowB = b.toLowerCase();
return lowA.contains(lowB) || lowB.contains(lowA);
}
/// Checks if string value is camelcase.
/// 检查字符串值是否驼峰大小写。
static bool isCamelCase(String s) =>
s == TransformUtils.camelCase(s);
/// Checks if string value is capitalize.
/// 检查字符串值是否大写
static bool isCapitalize(String s, {bool firstOnly = false}) =>
s == TransformUtils.capitalize(s, firstOnly: firstOnly);
}
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/file/file_utils.dart | Dart |
import 'dart:convert';
import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'package:yc_flutter_utils/log/log_utils.dart';
class FileUtils {
//FileSystemException: Cannot open file, path =
//'/data/user/0/com.didi.global.rider/app_flutter/map_hot.json'
//(OS Error: No such file or directory, errno = 2)
//解决办法:发生此错误的原因可能是该文件可能尚不存在。所以你应该在打开文件之前检查文件是否存在。
static final String TAG = "FileUtils";
/// 临时目录: /data/user/0/com.yc.utils/cache
/// 获取一个临时目录(缓存),系统可以随时清除。
static Future<String> getTempDir() async {
try {
Directory tempDir = await getTemporaryDirectory();
return tempDir.path;
} catch (err) {
LogUtils.e(err,tag:TAG);
return null;
}
}
/// 文档目录: /data/user/0/com.yc.utils/xxx
/// 获取应用程序的目录,用于存储只有它可以访问的文件。只有当应用程序被删除时,系统才会清除目录。
static Future<String> getAppDocDir() async {
try {
Directory appDocDir = await getApplicationDocumentsDirectory();
return appDocDir.path;
} catch (err) {
LogUtils.e(err,tag: TAG);
return null;
}
}
///初始化文件路径,默认选中应用程序的目录
static Future<File> getAppFile(String fileName) async {
//获取存储路径
final filePath = await getAppDocDir();
if(filePath == null){
return null;
}
//或者file对象(操作文件记得导入import 'dart:io')
return new File(filePath + "/" + fileName);
}
///获取存在文件中的数据,默认读到应用程序的目录
///使用async、await,返回是一个Future对象
static Future<String> readStringDir(String fileName) async {
try {
final file = await getAppFile(fileName);
return await file.readAsString();
} catch (err) {
LogUtils.e(err,tag: TAG);
return null;
}
}
/// 写入json文件,默认写到应用程序的目录
static Future<File> writeJsonFileDir(Object obj,String fileName) async {
if(obj==null){
return null;
}
try {
final file = await getAppFile(fileName);
return await file.writeAsString(json.encode(obj));
} catch (err) {
LogUtils.e(err,tag: TAG);
return null;
}
}
///利用文件存储字符串,默认写到应用程序的目录
static Future<File> writeStringDir(String string , String filePath) async {
if(string==null){
return null;
}
try {
final file = await getAppFile(filePath);
return await file.writeAsString(string);
} catch (err) {
LogUtils.e(err,tag: TAG);
return null;
}
}
///清除缓存数据
static Future<bool> clearFileDataDir(String fileName) async{
try {
final file = await getAppFile(fileName);
file.writeAsStringSync("");
return true;
} catch (err) {
LogUtils.e(err,tag: TAG);
return false;
}
}
///删除缓存文件
static Future<bool> deleteFileDataDir(String fileName) async{
try {
final file = await getAppFile(fileName);
file.delete();
return true;
} catch (err) {
LogUtils.e(err,tag: TAG);
return false;
}
}
///下面这些方法需要传递自定义存储路径-----------------------------------------------
///创建file文件
static File readFile(filePath) {
return new File('$filePath');
}
/// 写入json文件,自定义路径
static Future<File> writeJsonCustomFile(Object obj,String filePath) async {
if(obj==null){
return null;
}
try {
final file = readFile(filePath);
return await file.writeAsString(json.encode(obj));
} catch (err) {
LogUtils.e(err,tag: TAG);
return null;
}
}
///利用文件存储字符串,自定义路径
static Future<File> writeStringFile(String string , String filePath) async {
if(string==null){
return null;
}
try {
final file = readFile(filePath);
return await file.writeAsString(string);
} catch (err) {
LogUtils.e(err,tag: TAG);
return null;
}
}
///获取自定义路径文件存中的数据
///使用async、await,返回是一个Future对象
static Future<String> readStringCustomFile(String filePath) async {
try {
final file = readFile(filePath);
return await file.readAsString();
} catch (err) {
LogUtils.e(err,tag: TAG);
return null;
}
}
///清除缓存数据
static Future<bool> clearFileData(String filePath) async{
try {
final file = readFile(filePath);
file.writeAsStringSync("");
return true;
} catch (err) {
LogUtils.e(err,tag: TAG);
return false;
}
}
///删除缓存文件
static Future<bool> deleteFileData(String filePath) async{
try {
final file = readFile(filePath);
file.delete();
return true;
} catch (err) {
LogUtils.e(err,tag: TAG);
return false;
}
}
} | yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/file/storage_utils.dart | Dart |
import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'package:yc_flutter_utils/object/object_utils.dart';
/// 存储文件管理类
class StorageUtils {
/// getTemporaryDirectory
/// 指向设备上临时目录的路径,该目录没有备份,适合存储下载文件的缓存。
/// 此目录中的文件可以随时清除。这不会返回一个新的临时目录。
/// 相反,调用者负责在这个目录中创建(和清理)文件或目录。这个目录的作用域是调用应用程序。
/// 在iOS上,它使用“NSCachesDirectory”API。
/// 在Android上,它在上下文中使用“getCacheDir”API。
static Future<Directory> _initTempDir() {
//获取一个临时目录(缓存),系统可以随时清除。
return getTemporaryDirectory();
}
/// getApplicationSupportDirectory
/// 应用程序可以放置应用程序支持文件的目录的路径。
/// 对不希望向用户公开的文件使用此选项。您的应用程序不应将此目录用于用户数据文件。
/// 在iOS上,它使用“NSApplicationSupportDirectory”API。如果此目录不存在,则自动创建。
/// 在Android上,此函数抛出一个[UnsupportedError]。
static Future<Directory> _initSupportDir() {
//应用程序支持文件的目录的路径
return getApplicationSupportDirectory();
}
/// getApplicationDocumentsDirectory
/// 获取应用程序的目录,用于存储只有它可以访问的文件。只有当应用程序被删除时,系统才会清除目录。
/// 在iOS上,它使用“NSDocumentDirectory”API。如果数据不是用户生成的,请考虑使用[GetApplicationSupportDirectory]。
/// 在Android上,这在上下文中使用了“getDataDirectory”API。如果数据对用户可见,请考虑改用getExternalStorageDirectory。
static Future<Directory> _initAppDocDir() async {
//获取应用程序的目录,用于存储只有它可以访问的文件。只有当应用程序被删除时,系统才会清除目录。
return getApplicationDocumentsDirectory();
}
/// getExternalStorageDirectory
/// 应用程序可以访问顶层存储的目录的路径。在发出这个函数调用之前,应该确定当前操作系统,因为这个功能只在Android上可用。
/// 在iOS上,这个函数抛出一个[UnsupportedError],因为它不可能访问应用程序的沙箱之外。
/// 在Android上,它使用“getExternalStorageDirectory”API。
static Future<Directory> _initStorageDir() async {
//应用程序可以访问顶层存储的目录的路径。
return getExternalStorageDirectory();
}
/// 同步创建文件
static Directory createDir(String path) {
if (ObjectUtils.isEmpty(path)) {
return null;
}
Directory dir = Directory(path);
if (!dir.existsSync()) {
dir.createSync(recursive: true);
}
return dir;
}
/// 异步创建文件
static Future<Directory> createDirSync(String path) async {
if (ObjectUtils.isEmpty(path)) {
return null;
}
Directory dir = Directory(path);
bool exist = await dir.exists();
if (!exist) {
dir = await dir.create(recursive: true);
}
return dir;
}
/// 获取设备上临时目录的路径,该目录没有备份,适合存储下载文件的缓存。
/// fileName 文件名
/// dirName 文件夹名
/// String path = StorageUtil.getTempPath(fileName: 'demo.png', dirName: 'image');
static Future<String> getTempPath({String fileName, String dirName,}) async {
Directory _tempDir = await _initTempDir();
if (_tempDir == null) {
return null;
}
StringBuffer sb = StringBuffer("${_tempDir.path}");
if (!ObjectUtils.isEmpty(dirName)) {
sb.write("/$dirName");
await createDir(sb.toString());
}
if (!ObjectUtils.isEmpty(fileName)) sb.write("/$fileName");
return sb.toString();
}
/// 获取应用程序的目录,用于存储只有它可以访问的文件。只有当应用程序被删除时,系统才会清除目录。
/// fileName 文件名
/// dirName 文件夹名
/// String path = StorageUtil.getAppDocPath(fileName: 'demo.mp4', dirName: 'video');
static Future<String> getAppDocPath({String fileName, String dirName,}) async {
Directory _appDocDir = await _initAppDocDir();
if (_appDocDir == null) {
return null;
}
StringBuffer sb = StringBuffer("${_appDocDir.path}");
if (!ObjectUtils.isEmpty(dirName)) {
sb.write("/$dirName");
await createDir(sb.toString());
}
if (!ObjectUtils.isEmpty(fileName)) sb.write("/$fileName");
return sb.toString();
}
///
/// fileName 文件名
/// dirName 文件夹名
static Future<String> getStoragePath({String fileName, String dirName,}) async {
Directory _storageDir = await _initStorageDir();
if (_storageDir == null) {
return null;
}
StringBuffer sb = StringBuffer("${_storageDir.path}");
if (!ObjectUtils.isEmpty(dirName)) {
sb.write("/$dirName");
await createDir(sb.toString());
}
if (!ObjectUtils.isEmpty(fileName)){
sb.write("/$fileName");
}
return sb.toString();
}
/// 创建临时目录
/// dirName 文件夹名
/// String path = StorageUtil.createTempDir( dirName: 'image');
static Future<Directory> createTempDir({String dirName}) async {
Directory _tempDir = await _initTempDir();
if (_tempDir == null) {
return null;
}
StringBuffer sb = StringBuffer("${_tempDir.path}");
if (!ObjectUtils.isEmpty(dirName)){
sb.write("/$dirName");
}
return createDir(sb.toString());
}
/// 创建获取应用程序的目录
/// fileName 文件名
/// dirName 文件夹名
/// String path = StorageUtil.getAppDocPath(fileName: 'demo.mp4', dirName: 'video');
static Future<Directory> createAppDocDir({String dirName}) async {
Directory _appDocDir = await _initAppDocDir();
if (_appDocDir == null) {
return null;
}
StringBuffer sb = StringBuffer("${_appDocDir.path}");
if (!ObjectUtils.isEmpty(dirName)) {
sb.write("/$dirName");
}
return createDir(sb.toString());
}
/// dirName 文件夹名
/// category 分类,例如:video,image等等
/// String path = StorageUtil.getStoragePath(fileName: 'yc.apk', dirName: 'apk');
static Future<Directory> createStorageDir({String dirName}) async {
Directory _storageDir = await _initStorageDir();
if (_storageDir == null) {
return null;
}
StringBuffer sb = StringBuffer("${_storageDir.path}");
if (!ObjectUtils.isEmpty(dirName)) {
sb.write("/$dirName");
}
return createDir(sb.toString());
}
} | yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/flutter_utils.dart | Dart | library flutter_utils;
export 'package:yc_flutter_utils/base/base_constants.dart';
export 'package:yc_flutter_utils/base/base_method_constants.dart';
export 'package:yc_flutter_utils/bus/event_bus_service.dart';
export 'package:yc_flutter_utils/calcu/calculate_utils.dart';
export 'package:yc_flutter_utils/color/color_utils.dart';
export 'package:yc_flutter_utils/date/data_formats.dart';
export 'package:yc_flutter_utils/date/date_utils.dart';
export 'package:yc_flutter_utils/encrypt/encrypt_utils.dart';
export 'package:yc_flutter_utils/except/handle_exception.dart';
export 'package:yc_flutter_utils/extens/extension_int.dart';
export 'package:yc_flutter_utils/extens/extension_list.dart';
export 'package:yc_flutter_utils/extens/extension_map.dart';
export 'package:yc_flutter_utils/extens/extension_num.dart';
export 'package:yc_flutter_utils/extens/extension_set.dart';
export 'package:yc_flutter_utils/extens/extension_string.dart';
export 'package:yc_flutter_utils/extens/transform_utils.dart';
export 'package:yc_flutter_utils/extens/validator_utils.dart';
export 'package:yc_flutter_utils/file/file_utils.dart';
export 'package:yc_flutter_utils/file/storage_utils.dart';
export 'package:yc_flutter_utils/i18/extension.dart';
export 'package:yc_flutter_utils/i18/localizations.dart';
export 'package:yc_flutter_utils/i18/template_time.dart';
export 'package:yc_flutter_utils/image/image_utils.dart';
export 'package:yc_flutter_utils/json/json_utils.dart';
export 'package:yc_flutter_utils/locator/get_it.dart';
export 'package:yc_flutter_utils/log/log_utils.dart';
export 'package:yc_flutter_utils/num/decimal.dart';
export 'package:yc_flutter_utils/num/money_format.dart';
export 'package:yc_flutter_utils/num/money_unit.dart';
export 'package:yc_flutter_utils/num/num_utils.dart';
export 'package:yc_flutter_utils/num/rational.dart';
export 'package:yc_flutter_utils/object/object_utils.dart';
export 'package:yc_flutter_utils/regex/regex_constants.dart';
export 'package:yc_flutter_utils/regex/regex_utils.dart';
export 'package:yc_flutter_utils/router/fade_route.dart';
export 'package:yc_flutter_utils/router/navigator_utils.dart';
export 'package:yc_flutter_utils/router/navigator_utils.dart';
export 'package:yc_flutter_utils/screen/screen_utils.dart';
export 'package:yc_flutter_utils/text/text_utils.dart';
export 'package:yc_flutter_utils/time/abs_time_info.dart';
export 'package:yc_flutter_utils/time/day_format.dart';
export 'package:yc_flutter_utils/time/en_info_impl.dart';
export 'package:yc_flutter_utils/time/en_normal_info_impl.dart';
export 'package:yc_flutter_utils/time/time_utils.dart';
export 'package:yc_flutter_utils/time/zh_info_impl.dart';
export 'package:yc_flutter_utils/time/zh_normal_info_impl.dart';
export 'package:yc_flutter_utils/timer/task_queue_utils.dart';
export 'package:yc_flutter_utils/timer/timer_utils.dart';
export 'package:yc_flutter_utils/utils/enum_utils.dart';
export 'package:yc_flutter_utils/utils/flutter_init_utils.dart';
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/i18/extension.dart | Dart | import 'package:flutter/material.dart';
import 'package:yc_flutter_utils/i18/localizations.dart';
/// extension 拓展类。extension methods,顾名思义,就是扩展方法
/// on 表示
/// 扩展类名:一般没用到。该案例拓展类名:LocatizationExtensionState
extension LocatizationExtensionState on State {
///扩展方法:自定义的扩展方法,扩展方法数量无限,不可以和特定类型里已有方法的方法名相同,否则会报错或无效;
String getString(String id) {
if (id == null || id.isEmpty) {
return "";
}
return AppLocalizations.of(context).getString(id);
}
}
/// 使用扩展方法地方必须import扩展类所在文件
/// 注:如果没有import扩展类所在的文件,会找不到扩展方法
/// 使用:var name = context.getString("name");
extension LocatizationExtensionContext on BuildContext {
String getString(String id) {
if (id == null || id.isEmpty) {
return "";
}
return AppLocalizations.of(this).getString(id);
}
}
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/i18/localizations.dart | Dart | import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:yc_flutter_utils/log/log_utils.dart';
class AppLocalizations {
static const String TAG = "AppLocalizations";
/// 路径
static var assets = "assets/string/";
/// i18n 库支持的语言
/// 扩展位置,写在 main 函数中 runApp 之前
static var supportedLocales = [
const Locale('zh', 'CN'),
];
static Map<String, dynamic> _localizedValues;
final Locale locale;
static String package;
AppLocalizations(this.locale) {
LogUtils.d('i18n',tag: TAG);
}
static AppLocalizations of(BuildContext context) {
return Localizations.of<AppLocalizations>(context, AppLocalizations);
}
static Future<AppLocalizations> _load(Locale locale) async {
AppLocalizations translations = new AppLocalizations(locale);
String jsonContent;
LogUtils.d('load package = $package',tag: TAG);
String path ;
//比如:zh_CN.json
//languageCode就是:zh
//countryCode就是:CN
if (package == null) {
String languageCode = locale.languageCode;
String countryCode = locale.countryCode;
LogUtils.d('load languageCode = $languageCode , '
'countryCode = $countryCode',tag: TAG);
path = "$assets${languageCode}_$countryCode.json";
} else {
path = "packages/$package/$assets${locale.languageCode}_${locale.countryCode}.json";
}
LogUtils.d('load path = $path',tag: TAG);
jsonContent = await rootBundle.loadString(path);
_localizedValues = json.decode(jsonContent);
return translations;
}
static bool _isSupported(Locale locale) {
for (final supportedLocale in supportedLocales) {
if (supportedLocale.countryCode == locale.countryCode &&
supportedLocale.languageCode == locale.languageCode) {
return true;
}
}
return false;
}
///获取字符串信息
String getString(String key) {
LogUtils.d('getString = $key',tag: TAG);
return _localizedValues[key];
}
}
class AppLocalizationsDelegate extends LocalizationsDelegate<AppLocalizations> {
const AppLocalizationsDelegate();
@override
bool isSupported(Locale locale) => AppLocalizations._isSupported((locale));
@override
Future<AppLocalizations> load(Locale locale) async {
return AppLocalizations._load(locale);
}
@override
bool shouldReload(AppLocalizationsDelegate old) => false;
}
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/i18/template_time.dart | Dart | import 'package:flutter/cupertino.dart';
import 'package:yc_flutter_utils/date/date_utils.dart';
///国际化格式时间
class TemplateTime {
static Map<String, String> dateFormat1 = {
"zh_CN": "HH:mm",
};
static Map<String, String> dateFormat2 = {
"zh_CN": "yyyy年MM月dd日",
};
static String getFormatTemplate(Locale locale, Map format) {
String language = "${locale.languageCode}_${locale.countryCode}";
return format[language];
}
}
class LocalizationTime {
static Locale locale;
static String getFormat1(int timestamp) {
return _getFormat(locale, timestamp, TemplateTime.dateFormat1);
}
static String getFormat2(int timestamp) {
return _getFormat(locale, timestamp, TemplateTime.dateFormat2);
}
static String _getFormat(Locale locale, int timestamp,
Map<String, String> mapTemplate) {
var formatTemplate = TemplateTime.getFormatTemplate(locale, mapTemplate);
String formatDateMs = DateUtils.formatDateMilliseconds(timestamp,format: formatTemplate);
return formatDateMs;
}
}
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/image/image_utils.dart | Dart |
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/services.dart';
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';
/// 图片工具类
class ImageUtils {
///将base64流转化为图片
static MemoryImage base64ToImage(String base64String) {
return MemoryImage(
base64Decode(base64String),
);
}
///将base64流转化为Uint8List对象
static Uint8List base64ToUnit8list(String base64String) {
return base64Decode(base64String);
}
///将图片file转化为base64
static String fileToBase64(File imgFile) {
return base64Encode(imgFile.readAsBytesSync());
}
///将网络链接图片转化为base64
static Future networkImageToBase64(String url) async {
http.Response response = await http.get(url);
return base64.encode(response.bodyBytes);
}
///将asset图片转化为base64
Future assetImageToBase64(String path) async {
ByteData bytes = await rootBundle.load(path);
return base64.encode(Uint8List.view(bytes.buffer));
}
///加载网络图片,并且指定宽高大小。使用默认预加载loading和错误视图
static CachedNetworkImage showNetImageWh(String url, double width, double height) {
return CachedNetworkImage(
width: width,
height: height,
imageUrl: url ?? '',
imageBuilder: (context, imageProvider) => Container(
decoration: BoxDecoration(
image: DecorationImage(
image: imageProvider,
fit: BoxFit.cover,
colorFilter:
ColorFilter.mode(Colors.transparent, BlendMode.colorBurn)),
),
),
placeholder: (context, url) => Center(
child: Container(
height: 40,
width: 40,
margin: EdgeInsets.all(5),
child: CircularProgressIndicator(
strokeWidth: 2.0,
valueColor: AlwaysStoppedAnimation(Colors.blue),
),
),
),
errorWidget: (context, url, error) => Container(
child: Icon(
Icons.terrain,
size: 64,
),
alignment: Alignment.center,
color: Colors.black12,
),
);
}
///加载网络图片,并且指定宽高大小。切割圆角
static CachedNetworkImage showNetImageWhClip(String url,
double width, double height , double circular) {
return CachedNetworkImage(
width: width,
height: height,
imageUrl: url ?? '',
imageBuilder: (context, imageProvider) => Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(circular),
image: DecorationImage(
image: imageProvider,
fit: BoxFit.cover,
colorFilter:
ColorFilter.mode(Colors.transparent, BlendMode.colorBurn)),
),
),
placeholder: (context, url) => Center(
child: Container(
height: 40,
width: 40,
margin: EdgeInsets.all(5),
child: CircularProgressIndicator(
strokeWidth: 2.0,
valueColor: AlwaysStoppedAnimation(Colors.blue),
),
),
),
errorWidget: (context, url, error) => Container(
child: Icon(
Icons.terrain,
size: 64,
),
alignment: Alignment.center,
color: Colors.black12,
),
);
}
///加载网络图片,切割圆形图片。
static CachedNetworkImage showNetImageCircle(String url, double radius) {
return CachedNetworkImage(
width: radius * 2,
height: radius * 2,
imageUrl: url ?? '',
imageBuilder: (context, imageProvider) => Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(radius),
image: DecorationImage(
image: imageProvider,
fit: BoxFit.cover,
colorFilter:
ColorFilter.mode(Colors.transparent, BlendMode.colorBurn)),
),
),
placeholder: (context, url) => Center(
child: Container(
height: 40,
width: 40,
margin: EdgeInsets.all(5),
child: CircularProgressIndicator(
strokeWidth: 2.0,
valueColor: AlwaysStoppedAnimation(Colors.blue),
),
),
),
errorWidget: (context, url, error) => Container(
child: Icon(
Icons.terrain,
size: 64,
),
alignment: Alignment.center,
color: Colors.black12,
),
);
}
///加载网络图片,并且指定宽高大小。传入错误视图
static CachedNetworkImage showNetImageWhError(String url,
double width, double height , LoadingErrorWidgetBuilder error) {
return CachedNetworkImage(
width: width,
height: height,
imageUrl: url ?? '',
imageBuilder: (context, imageProvider) => Container(
decoration: BoxDecoration(
image: DecorationImage(
image: imageProvider,
fit: BoxFit.cover,
colorFilter:
ColorFilter.mode(Colors.transparent, BlendMode.colorBurn)),
),
),
placeholder: (context, url) => Center(
child: Container(
height: 40,
width: 40,
margin: EdgeInsets.all(5),
child: CircularProgressIndicator(
strokeWidth: 2.0,
valueColor: AlwaysStoppedAnimation(Colors.blue),
),
),
),
errorWidget: error
);
}
///加载网络图片,并且指定宽高大小。传入预加载,错误视图
static CachedNetworkImage showNetImageWhPlaceError(String url,
double width, double height ,PlaceholderWidgetBuilder place,
LoadingErrorWidgetBuilder error) {
return CachedNetworkImage(
width: width,
height: height,
imageUrl: url ?? '',
imageBuilder: (context, imageProvider) => Container(
decoration: BoxDecoration(
image: DecorationImage(
image: imageProvider,
fit: BoxFit.cover,
colorFilter:
ColorFilter.mode(Colors.transparent, BlendMode.colorBurn)),
),
),
placeholder: place,
errorWidget: error
);
}
} | yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/json/json_utils.dart | Dart | import 'dart:convert';
import 'package:yc_flutter_utils/log/log_utils.dart';
/// json 格式转化工具类
class JsonUtils {
/// 单纯的Json格式输出打印
static void printJson(Object object) {
try {
JsonEncoder encoder = JsonEncoder.withIndent(' ');
var encoderString = encoder.convert(object);
LogUtils.i(encoderString,tag: "json:");
} catch (e) {
LogUtils.e(e,tag: "json:");
}
}
/// 单纯的Json格式输出打印
static void printJsonEncode(Object object) {
try {
var encoderString = json.encode(object);
LogUtils.i(encoderString,tag: "json:");
} catch (e) {
LogUtils.e(e,tag: "json:");
}
}
/// 将对象[值]转换为JSON字符串
/// Converts object [value] to a JSON string.
static String encodeObj(dynamic value) {
return value == null ? null : json.encode(value);
}
/// 转换JSON字符串到对象
/// Converts JSON string [source] to object.
static T getObj<T>(String source, T f(Map v)) {
if (source == null || source.isEmpty) return null;
try {
Map map = json.decode(source);
return f(map);
} catch (e) {
print('JsonUtils convert error, Exception:${e.toString()}');
}
return null;
}
/// 转换JSON字符串或JSON映射[源]到对象
/// Converts JSON string or JSON map [source] to object.
static T getObject<T>(dynamic source, T f(Map v)) {
if (source == null || source.toString().isEmpty) return null;
try {
Map map;
if (source is String) {
map = json.decode(source);
} else {
map = source;
}
return f(map);
} catch (e) {
print('JsonUtils convert error, Exception:${e.toString()}');
}
return null;
}
/// 转换JSON字符串列表[源]到对象列表
/// Converts JSON string list [source] to object list.
static List<T> getObjList<T>(String source, T f(Map v)) {
if (source == null || source.isEmpty) return null;
try {
List list = json.decode(source);
return list.map((value) {
if (value is String) {
value = json.decode(value);
}
return f(value);
}).toList();
} catch (e) {
print('JsonUtils convert error, Exception:${e.toString()}');
}
return null;
}
/// 转换JSON字符串或JSON映射列表[源]到对象列表
/// Converts JSON string or JSON map list [source] to object list.
static List<T> getObjectList<T>(dynamic source, T f(Map v)) {
if (source == null || source.toString().isEmpty) return null;
try {
List list;
if (source is String) {
list = json.decode(source);
} else {
list = source;
}
return list.map((value) {
if (value is String) {
value = json.decode(value);
}
return f(value);
}).toList();
} catch (e) {
print('JsonUtils convert error, Exception:${e.toString()}');
}
return null;
}
/// get List
static List<T> getList<T>(dynamic source) {
List list;
if (source is String) {
list = json.decode(source);
} else {
list = source;
}
return list?.map((v) {
return v as T;
})?.toList();
}
}
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/locator/get_it.dart | Dart | library get_it;
import 'dart:async';
import 'package:async/async.dart';
import 'package:flutter/material.dart';
part 'get_it_impl.dart';
/// If your singleton that you register wants to use the manually signalling
/// of its ready state, it can implement this interface class instead of using
/// the [signalsReady] parameter of the registration functions
/// (you don't really have to implement much ;-) )
abstract class WillSignalReady {}
/// Signature of the factory function used by non async factories
typedef FactoryFunc<T> = T Function();
/// For Factories that expect up to two parameters if you need only one use `void` for the one
/// you don't use
typedef FactoryFuncParam<T, P1, P2> = T Function(P1 param1, P2 param2);
/// Signature of the factory function used by async factories
typedef FactoryFuncAsync<T> = Future<T> Function();
/// Signature for disposing function
/// because closures like `(x){}` have a return type of Null we don't use `FutureOr<void>`
typedef DisposingFunc<T> = FutureOr Function(T param);
/// Signature for disposing function on scope level
typedef ScopeDisposeFunc = FutureOr Function();
/// For async Factories that expect up to two parameters if you need only one use `void` for the one
/// you don't use
typedef FactoryFuncParamAsync<T, P1, P2> = Future<T> Function(
P1 param1, P2 param2);
class WaitingTimeOutException implements Exception {
/// In case of an timeout while waiting for an instance to get ready
/// This exception is thrown whith information about who is still waiting
///
/// if you pass the [callee] parameter to [isReady], or define dependent Singletons
/// this maps lists which callees is waiting for whom
final Map<String, List<String>> areWaitedBy;
/// Lists with Types that are still not ready
final List<String> notReadyYet;
/// Lists with Types that are already ready
final List<String> areReady;
WaitingTimeOutException(this.areWaitedBy, this.notReadyYet, this.areReady)
: assert(areWaitedBy != null && notReadyYet != null && areReady != null);
@override
String toString() {
// ignore: avoid_print
print(
'GetIt: There was a timeout while waiting for an instance to signal ready');
// ignore: avoid_print
print('The following instance types where waiting for completion');
for (final entry in areWaitedBy.entries) {
// ignore: avoid_print
print('${entry.value} is waiting for ${entry.key}');
}
// ignore: avoid_print
print('The following instance types have NOT signalled ready yet');
for (final entry in notReadyYet) {
// ignore: avoid_print
print(entry);
}
// ignore: avoid_print
print('The following instance types HAVE signalled ready yet');
for (final entry in areReady) {
// ignore: avoid_print
print(entry);
}
return super.toString();
}
}
/// Very simple and easy to use service locator
/// You register your object creation factory or an instance of an object with [registerFactory],
/// [registerSingleton] or [registerLazySingleton]
/// And retrieve the desired object using [get] or call your locator das as function as its a
/// callable class
/// Additionally GetIt offers asynchronous creation functions as well as functions to synchronize
/// the async initialization of multiple Singletons
abstract class GetIt {
static GetIt _instance;
/// access to the Singleton instance of GetIt
static GetIt get instance {
// ignore: join_return_with_assignment
_instance ??= _GetItImplementation();
return _instance;
}
/// Short form to access the instance of GetIt
static GetIt get I => instance;
/// If you need more than one instance of GetIt you can use [asNewInstance()]
/// You should prefer to use the `instance()` method to access the global instance of [GetIt].
factory GetIt.asNewInstance() {
return _GetItImplementation();
}
/// By default it's not allowed to register a type a second time.
/// If you really need to you can disable the asserts by setting[allowReassignment]= true
bool allowReassignment = false;
/// retrieves or creates an instance of a registered type [T] depending on the registration
/// function used for this type or based on a name.
/// for factories you can pass up to 2 parameters [param1,param2] they have to match the types
/// given at registration with [registerFactoryParam()]
T get<T>({String instanceName, dynamic param1, dynamic param2});
/// Returns an Future of an instance that is created by an async factory or a Singleton that is
/// not ready with its initialization.
/// for async factories you can pass up to 2 parameters [param1,param2] they have to match the types
/// given at registration with [registerFactoryParamAsync()]
Future<T> getAsync<T>({String instanceName, dynamic param1, dynamic param2});
/// Callable class so that you can write `GetIt.instance<MyType>` instead of
/// `GetIt.instance.get<MyType>`
T call<T>({String instanceName, dynamic param1, dynamic param2});
/// registers a type so that a new instance will be created on each call of [get] on that type
/// [T] type to register
/// [factoryfunc] factory function for this type
/// [instanceName] if you provide a value here your factory gets registered with that
/// name instead of a type. This should only be necessary if you need to register more
/// than one instance of one type. Its highly not recommended
void registerFactory<T>(FactoryFunc<T> factoryfunc, {String instanceName});
/// registers a type so that a new instance will be created on each call of [get] on that type based on
/// up to two parameters provided to [get()]
/// [T] type to register
/// [P1] type of param1
/// [P2] type of param2
/// if you use only one parameter pass void here
/// [factoryfunc] factory function for this type that accepts two parameters
/// [instanceName] if you provide a value here your factory gets registered with that
/// name instead of a type. This should only be necessary if you need to register more
/// than one instance of one type. Its highly not recommended
///
/// example:
/// getIt.registerFactoryParam<TestClassParam,String,int>((s,i)
/// => TestClassParam(param1:s, param2: i));
///
/// if you only use one parameter:
///
/// getIt.registerFactoryParam<TestClassParam,String,void>((s,_)
/// => TestClassParam(param1:s);
void registerFactoryParam<T, P1, P2>(FactoryFuncParam<T, P1, P2> factoryfunc,
{String instanceName});
/// registers a type so that a new instance will be created on each call of [getAsync] on that type
/// the creation function is executed asynchronously and has to be accessed with [getAsync]
/// [T] type to register
/// [factoryfunc] async factory function for this type
/// [instanceName] if you provide a value here your factory gets registered with that
/// name instead of a type. This should only be necessary if you need to register more
/// than one instance of one type. Its highly not recommended
void registerFactoryAsync<T>(FactoryFuncAsync<T> factoryfunc,
{String instanceName});
/// registers a type so that a new instance will be created on each call of [getAsync]
/// on that type based on up to two parameters provided to [getAsync()]
/// the creation function is executed asynchronously and has to be accessed with [getAsync]
/// [T] type to register
/// [P1] type of param1
/// [P2] type of param2
/// if you use only one parameter pass void here
/// [factoryfunc] factory function for this type that accepts two parameters
/// [instanceName] if you provide a value here your factory gets registered with that
/// name instead of a type. This should only be necessary if you need to register more
/// than one instance of one type. Its highly not recommended
///
/// example:
/// getIt.registerFactoryParam<TestClassParam,String,int>((s,i) async
/// => TestClassParam(param1:s, param2: i));
///
/// if you only use one parameter:
///
/// getIt.registerFactoryParam<TestClassParam,String,void>((s,_) async
/// => TestClassParam(param1:s);
void registerFactoryParamAsync<T, P1, P2>(
FactoryFuncParamAsync<T, P1, P2> factoryfunc,
{String instanceName});
/// registers a type as Singleton by passing an [instance] of that type
/// that will be returned on each call of [get] on that type
/// [T] type to register
/// [instanceName] if you provide a value here your instance gets registered with that
/// name instead of a type. This should only be necessary if you need to register more
/// than one instance of one type. Its highly not recommended
/// If [signalsReady] is set to `true` it means that the future you can get from `allReady()`
/// cannot complete until this this instance was signalled ready by calling [signalsReady(instance)].
void registerSingleton<T>(T instance,
{String instanceName, bool signalsReady, DisposingFunc<T> dispose});
/// registers a type as Singleton by passing an factory function of that type
/// that will be called on each call of [get] on that type
/// [T] type to register
/// [instanceName] if you provide a value here your instance gets registered with that
/// name instead of a type. This should only be necessary if you need to register more
/// than one instance of one type. Its highly not recommended
/// [dependsOn] if this instance depends on other registered Singletons before it can be initilaized
/// you can either orchestrate this manually using [isReady()] or pass a list of the types that the
/// instance depends on here. [factoryFunc] won't get executed till this types are ready.
/// [func] is called
/// If [signalsReady] is set to `true` it means that the future you can get from `allReady()`
/// cannot complete until this this instance was signalled ready by calling [signalsReady(instance)].
void registerSingletonWithDependencies<T>(FactoryFunc<T> factoryFunc,
{String instanceName,
Iterable<Type> dependsOn,
bool signalsReady,
DisposingFunc<T> dispose});
/// registers a type as Singleton by passing an asynchronous factory function which has to return the instance
/// that will be returned on each call of [get] on that type.
/// Therefore you have to ensure that the instance is ready before you use [get] on it or use [getAsync()] to
/// wait for the completion.
/// You can wait/check if the instance is ready by using [isReady()] and [isReadySync()].
/// [factoryfunc] is executed immediately if there are no dependencies to other Singletons (see below).
/// As soon as it returns, this instance is marked as ready unless you don't set [signalsReady==true]
/// [instanceName] if you provide a value here your instance gets registered with that
/// name instead of a type. This should only be necessary if you need to register more
/// than one instance of one type. Its highly not recommended
/// [dependsOn] if this instance depends on other registered Singletons before it can be initilaized
/// you can either orchestrate this manually using [isReady()] or pass a list of the types that the
/// instance depends on here. [factoryFunc] won't get executed till this types are ready.
/// If [signalsReady] is set to `true` it means that the future you can get from `allReady()` cannot complete until this
/// this instance was signalled ready by calling [signalsReady(instance)]. In that case no automatic ready signal
/// is made after completion of [factoryfunc]
void registerSingletonAsync<T>(FactoryFuncAsync<T> factoryfunc,
{String instanceName,
Iterable<Type> dependsOn,
bool signalsReady,
DisposingFunc<T> dispose});
/// registers a type as Singleton by passing a factory function that will be called
/// on the first call of [get] on that type
/// [T] type to register
/// [factoryfunc] factory function for this type
/// [instanceName] if you provide a value here your factory gets registered with that
/// name instead of a type. This should only be necessary if you need to register more
/// than one instance of one type. Its highly not recommended
/// [registerLazySingleton] does not influence [allReady] however you can wait
/// for and be dependent on a LazySingleton.
void registerLazySingleton<T>(FactoryFunc<T> factoryfunc,
{String instanceName, DisposingFunc<T> dispose});
/// registers a type as Singleton by passing a async factory function that will be called
/// on the first call of [getAsnc] on that type
/// This is a rather esoteric requirement so you should seldom have the need to use it.
/// This factory function [factoryFunc] isn't called immediately but wait till the first call by
/// [getAsync()] or [isReady()] is made
/// To control if an async Singleton has completed its [factoryFunc] gets a `Completer` passed
/// as parameter that has to be completed to signal that this instance is ready.
/// Therefore you have to ensure that the instance is ready before you use [get] on it or use [getAsync()] to
/// wait for the completion.
/// You can wait/check if the instance is ready by using [isReady()] and [isReadySync()].
/// [instanceName] if you provide a value here your instance gets registered with that
/// name instead of a type. This should only be necessary if you need to register more
/// than one instance of one type. Its highly not recommended.
/// [registerLazySingletonAsync] does not influence [allReady] however you can wait
/// for and be dependent on a LazySingleton.
void registerLazySingletonAsync<T>(FactoryFuncAsync<T> factoryFunc,
{String instanceName, DisposingFunc<T> dispose});
/// Tests if an [instance] of an object or aType [T] or a name [instanceName]
/// is registered inside GetIt
bool isRegistered<T>({Object instance, String instanceName});
/// Clears all registered types. Handy when writing unit tests
/// If you provided dispose function when registering they will be called
/// [dispose] if `false` it only resets without calling any dispose
/// functions
/// As dispose funcions can be async, you should await this function.
Future<void> reset({bool dispose = true});
/// Clears all registered types for the current scope
/// If you provided dispose function when registering they will be called
/// [dispose] if `false` it only resets without calling any dispose
/// functions
/// As dispose funcions can be async, you should await this function.
Future<void> resetScope({bool dispose = true});
/// Creates a new registration scope. If you register types after creating
/// a new scope they will hide any previous registration of the same type.
/// Scopes allow you to manage different live times of your Objects.
/// [scopeName] if you name a scope you can pop all scopes above the named one
/// by using the name.
/// [dispose] function that will be called when you pop this scope. The scope
/// is still valied while it is executed
void pushNewScope({String scopeName, ScopeDisposeFunc dispose});
/// Disposes all factories/Singletons that have ben registered in this scope
/// and pops (destroys) the scope so that the previous scope gets active again.
/// if you provided dispose functions on registration, they will be called.
/// if you passed a dispose function when you pushed this scope it will be
/// calles before the scope is popped.
/// As dispose funcions can be async, you should await this function.
Future<void> popScope();
/// if you have a lot of scopes with names you can pop (see [popScope]) all
/// scopes above the scope with [name] including that scope
/// Scopes are poped in order from the top
/// As dispose funcions can be async, you should await this function.
/// it no scope with [name] exists, nothing is popped and `false` is returned
Future<bool> popScopesTill(String name);
/// Clears the instance of a lazy singleton,
/// being able to call the factory function on the next call
/// of [get] on that type again.
/// you select the lazy Singleton you want to reset by either providing
/// an [instance], its registered type [T] or its registration name.
/// if you need to dispose some resources before the reset, you can
/// provide a [disposingFunction]. This function overrides the disposing
/// you might have provided when registering.
void resetLazySingleton<T>(
{Object instance,
String instanceName,
void Function(T) disposingFunction});
/// Unregister an [instance] of an object or a factory/singleton by Type [T] or by name [instanceName]
/// if you need to dispose any resources you can do it using [disposingFunction] function
/// that provides a instance of your class to be disposed. This function overrides the disposing
/// you might have provided when registering.
void unregister<T>(
{Object instance,
String instanceName,
void Function(T) disposingFunction});
/// returns a Future that completes if all asynchronously created Singletons and any Singleton that had
/// [signalsReady==true] are ready.
/// This can be used inside a FutureBuilder to change the UI as soon as all initialization
/// is done
/// If you pass a [timeout], an [WaitingTimeOutException] will be thrown if not all Singletons
/// were ready in the given time. The Exception contains details on which Singletons are not ready yet.
/// if [allReady] should not wait for the completion of async Signletons set
/// [ignorePendingAsyncCreation==true]
Future<void> allReady(
{Duration timeout, bool ignorePendingAsyncCreation = false});
/// Returns a Future that completes if the instance of an Singleton, defined by Type [T] or
/// by name [instanceName] or by passing the an existing [instance], is ready
/// If you pass a [timeout], an [WaitingTimeOutException] will be thrown if the instance
/// is not ready in the given time. The Exception contains details on which Singletons are
/// not ready at that time.
/// [callee] optional parameter which makes debugging easier. Pass `this` in here.
Future<void> isReady<T>({
Object instance,
String instanceName,
Duration timeout,
Object callee,
});
/// Checks if an async Singleton defined by an [instance], a type [T] or an [instanceName]
/// is ready without waiting
bool isReadySync<T>({Object instance, String instanceName});
/// Returns if all async Singletons are ready without waiting
/// if [allReady] should not wait for the completion of async Signletons set
/// [ignorePendingAsyncCreation==true]
// ignore: avoid_positional_boolean_parameters
bool allReadySync([bool ignorePendingAsyncCreation = false]);
/// Used to manually signal the ready state of a Singleton.
/// If you want to use this mechanism you have to pass [signalsReady==true] when registering
/// the Singleton.
/// If [instance] has a value GetIt will search for the responsible Singleton
/// and completes all futures that might be waited for by [isReady]
/// If all waiting singletons have signalled ready the future you can get
/// from [allReady] is automatically completed
///
/// Typically this is used in this way inside the registered objects init
/// method `GetIt.instance.signalReady(this);`
///
/// if [instance] is `null` and no factory/singleton is waiting to be signalled this
/// will complete the future you got from [allReady], so it can be used to globally
/// giving a ready Signal
///
/// Both ways are mutual exclusive, meaning either only use the global `signalReady()` and
/// don't register a singleton to signal ready or use any async registrations
///
/// Or use async registrations methods or let individual instances signal their ready
/// state on their own.
void signalReady(Object instance);
}
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/locator/get_it_helper.dart | Dart |
typedef FactoryFunc<T> = T Function();
/// ServiceLocator简单实现代码
class GetItHelper {
final _factories = new Map<Type, _ServiceFactory<dynamic>>();
/// 默认情况下,不允许第二次注册类型。
/// 如果你真的需要你可以通过设置[allowReassignment]= true禁用断言
bool allowReassignment = false;
/// 检索或创建一个注册类型[T]的实例,这取决于用于该类型的注册函数。
T get<T>() {
_ServiceFactory<T> object = _factories[T];
if (object == null) {
throw new Exception(
"Object of type ${T.toString()} is not registered inside GetIt");
}
return object.getObject();
}
T call<T>() {
return get<T>();
}
/// 注册一个类型,以便每次对该类型的[get]调用都会创建一个新实例
void registerFactory<T>(FactoryFunc<T> func) {
assert(allowReassignment || !_factories.containsKey(T),
"Type ${T.toString()} is already registered");
_factories[T] = new _ServiceFactory<T>(_ServiceFactoryType.alwaysNew,
creationFunction: func);
}
/// 通过传递一个工厂函数注册一个类型为Singleton,该工厂函数将在第一次调用该类型的[get]时被调用
void registerLazySingleton<T>(FactoryFunc<T> func) {
assert(allowReassignment || !_factories.containsKey(T),
"Type ${T.toString()} is already registered");
_factories[T] = new _ServiceFactory<T>(_ServiceFactoryType.lazy,
creationFunction: func);
}
/// 通过传递一个实例来注册一个类型为Singleton,该实例将在每次调用该类型的[get]时返回
void registerSingleton<T>(T instance) {
assert(allowReassignment || !_factories.containsKey(T),
"Type ${T.toString()} is already registered");
_factories[T] = new _ServiceFactory<T>(_ServiceFactoryType.constant,
instance: instance);
}
/// 清除所有已注册的类型。
void reset() {
_factories.clear();
}
}
enum _ServiceFactoryType { alwaysNew, constant, lazy }
class _ServiceFactory<T> {
_ServiceFactoryType type;
FactoryFunc creationFunction;
Object instance;
_ServiceFactory(this.type, {this.creationFunction, this.instance});
T getObject() {
try {
switch (type) {
case _ServiceFactoryType.alwaysNew:
return creationFunction() as T;
break;
case _ServiceFactoryType.constant:
return instance as T;
break;
case _ServiceFactoryType.lazy:
if (instance == null) {
instance = creationFunction();
}
return instance as T;
break;
}
} catch (e, s) {
print("Error while creating ${T.toString()}");
print('Stack trace:\n $s');
rethrow;
}
return null;
}
}
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/locator/get_it_impl.dart | Dart | part of 'get_it.dart';
/// Two handy function that helps me to express my intention clearer and shorter to check for runtime
/// errors
// ignore: avoid_positional_boolean_parameters
void throwIf(bool condition, Object error) {
if (condition) throw error;
}
// ignore: avoid_positional_boolean_parameters
void throwIfNot(bool condition, Object error) {
if (!condition) throw error;
}
/// You will see a rather esoteric looking test `(const Object() is! T)` at several places
/// /// it tests if [T] is a real type and not Object or dynamic
/// For each registered factory/singleton a [_ServiceFactory<T>] is created
/// it holds either the instance of a Singleton or/and the creation functions
/// for creating an instance when [get] is called
///
/// There are three different types
enum _ServiceFactoryType {
alwaysNew,
/// factory which means on every call of [get] a new instance is created
constant, // normal singleton
lazy, // lazy
}
/// If I use `Singleton` without specifier in the comments I mean normal and lazy
class _ServiceFactory<T, P1, P2> {
final _ServiceFactoryType factoryType;
Type param1Type;
Type param2Type;
/// Because of the different creation methods we need alternative factory functions
/// only one of them is always set.
final FactoryFunc<T> creationFunction;
final FactoryFuncAsync<T> asyncCreationFunction;
final FactoryFuncParam<T, P1, P2> creationFunctionParam;
final FactoryFuncParamAsync<T, P1, P2> asyncCreationFunctionParam;
/// Dispose function that is used when a scope is popped
final DisposingFunc<T> disposeFunction;
/// In case of a named registration the instance name is here stored for easy access
final String instanceName;
/// true if one of the async registration functions have been used
final bool isAsync;
/// If a an existing Object gets registered or an async/lazy Singleton has finished
/// its creation it is stored here
Object instance;
/// the type that was used when registering. used for runtime checks
Type registrationType;
/// to enable Singletons to signal that they are ready (their initialization is finished)
Completer _readyCompleter;
/// the returned future of pending async factory calls or facttory call with dependencies
Future<T> pendingResult;
/// If other objects are waiting for this one
/// they are stored here
final List<Type> objectsWaiting = [];
bool get isReady => _readyCompleter.isCompleted;
bool get isNamedRegistration => instanceName != null;
String get debugName => '$instanceName : $registrationType';
bool get canBeWaitedFor =>
shouldSignalReady || pendingResult != null || isAsync;
final bool shouldSignalReady;
_ServiceFactory(this.factoryType,
{this.creationFunction,
this.asyncCreationFunction,
this.creationFunctionParam,
this.asyncCreationFunctionParam,
this.instance,
this.isAsync = false,
this.instanceName,
@required this.shouldSignalReady,
this.disposeFunction}) {
registrationType = T;
param1Type = P1;
param2Type = P2;
_readyCompleter = Completer();
}
FutureOr dispose() {
return disposeFunction?.call(instance as T);
}
/// returns an instance depending on the type of the registration if [async==false]
T getObject(dynamic param1, dynamic param2) {
assert(
!(factoryType != _ServiceFactoryType.alwaysNew &&
(param1 != null || param2 != null)),
'You can only pass parameters to factories!');
try {
switch (factoryType) {
case _ServiceFactoryType.alwaysNew:
if (creationFunctionParam != null) {
// param1.runtimeType == param1Type should use 'is' but Dart does
// not support this comparison. For the time being it is therefore
// disabled
// assert(
// param1 == null || param1.runtimeType == param1Type,
// 'Incompatible Type passed as param1\n'
// 'expected: $param1Type actual: ${param1.runtimeType}');
// assert(
// param2 == null || param2.runtimeType == param2Type,
// 'Incompatible Type passed as param2\n'
// 'expected: $param2Type actual: ${param2.runtimeType}');
return creationFunctionParam(param1 as P1, param2 as P2);
} else {
return creationFunction();
}
break;
case _ServiceFactoryType.constant:
return instance as T;
break;
case _ServiceFactoryType.lazy:
if (instance == null) {
instance = creationFunction();
_readyCompleter.complete();
}
return instance as T;
break;
default:
throw StateError('Impossible factoryType');
}
} catch (e, s) {
// ignore: avoid_print
print('Error while creating ${T.toString()}');
// ignore: avoid_print
print('Stack trace:\n $s');
rethrow;
}
}
/// returns an async instance depending on the type of the registration if [async==true] or if [dependsOn.isnoEmpty].
Future<R> getObjectAsync<R>(dynamic param1, dynamic param2) async {
assert(
!(factoryType != _ServiceFactoryType.alwaysNew &&
(param1 != null || param2 != null)),
'You can only pass parameters to factories!');
throwIfNot(
isAsync || pendingResult != null,
StateError(
'You can only access registered factories/objects this way if they are created asynchronously'));
try {
switch (factoryType) {
case _ServiceFactoryType.alwaysNew:
if (asyncCreationFunctionParam != null) {
/* assert(
param1 == null || param1.runtimeType == param1Type,
'Incompatible Type passed a param1\n'
'expected: $param1Type actual: ${param1.runtimeType}');
assert(
param2 == null || param2.runtimeType == param2Type,
'Incompatible Type passed a param2\n'
'expected: $param2Type actual: ${param2.runtimeType}');
*/
return asyncCreationFunctionParam(param1 as P1, param2 as P2)
as Future<R>;
} else {
return asyncCreationFunction() as Future<R>;
}
break;
case _ServiceFactoryType.constant:
if (instance != null) {
return Future<R>.value(instance as R);
} else {
assert(pendingResult != null);
return pendingResult as Future<R>;
}
break;
case _ServiceFactoryType.lazy:
if (instance != null) {
// We already have a finished instance
return Future<R>.value(instance as R);
} else {
if (pendingResult !=
null) // an async creation is already in progress
{
return pendingResult as Future<R>;
}
/// Seems this is really the first access to this async Signleton
final asyncResult = asyncCreationFunction();
pendingResult = asyncResult.then((newInstance) {
if (!shouldSignalReady) {
///only complete automatically if the registration wasn't marked with [signalsReady==true]
_readyCompleter.complete();
}
instance = newInstance;
return newInstance;
});
return pendingResult as Future<R>;
}
break;
default:
throw StateError('Impossible factoryType');
}
} catch (e, s) {
// ignore: avoid_print
print('Error while creating ${T.toString()}');
// ignore: avoid_print
print('Stack trace:\n $s');
rethrow;
}
}
}
class _Scope {
final String name;
final ScopeDisposeFunc disposeFunc;
final factoriesByName =
<String, Map<Type, _ServiceFactory<dynamic, dynamic, dynamic>>>{};
_Scope({this.name, this.disposeFunc});
Future<void> reset({@required bool dispose}) async {
if (dispose) {
for (final _factory in allFactories) {
await _factory.dispose();
}
}
factoriesByName.clear();
}
List<_ServiceFactory> get allFactories => factoriesByName.values
.fold<List<_ServiceFactory>>([], (sum, x) => sum..addAll(x.values));
Future<void> dispose() async {
await disposeFunc?.call();
}
}
class _GetItImplementation implements GetIt {
static const _baseScopeName = 'baseScope';
final _scopes = [_Scope(name: _baseScopeName)];
_Scope get _currentScope => _scopes.last;
/// We still support a global ready signal mechanism for that we use this
/// Completer.
final _globalReadyCompleter = Completer();
/// By default it's not allowed to register a type a second time.
/// If you really need to you can disable the asserts by setting[allowReassignment]= true
@override
bool allowReassignment = false;
/// Is used by several other functions to retrieve the correct [_ServiceFactory]
_ServiceFactory<T, dynamic, dynamic>
_findFirstFactoryByNameAndTypeOrNull<T extends Object>(
String instanceName, [
Type type,
]) {
/// We use an assert here instead of an `if..throw` because it gets called on every call
/// of [get]
/// `(const Object() is! T)` tests if [T] is a real type and not Object or dynamic
assert(
type != null || const Object() is! T,
'GetIt: The compiler could not infer the type. You have to provide a type '
'and optionally a name. Did you accidentally do `var sl=GetIt.instance();` '
'instead of var sl=GetIt.instance;',
);
_ServiceFactory<T, dynamic, dynamic> instanceFactory;
int scopeLevel = _scopes.length - 1;
while (instanceFactory == null && scopeLevel >= 0) {
final factoryByTypes = _scopes[scopeLevel].factoriesByName[instanceName];
if (type == null) {
instanceFactory = factoryByTypes != null
? factoryByTypes[T] as _ServiceFactory<T, dynamic, dynamic>
: null;
} else {
/// in most cases we can rely on the generic type T because it is passed
/// in by callers. In case of dependent types this does not work as these types
/// are dynamic
instanceFactory = factoryByTypes != null
? factoryByTypes[type] as _ServiceFactory<T, dynamic, dynamic>
: null;
}
scopeLevel--;
}
return instanceFactory;
}
/// Is used by several other functions to retrieve the correct [_ServiceFactory]
_ServiceFactory _findFactoryByNameAndType<T extends Object>(
String instanceName, [
Type type,
]) {
final instanceFactory =
_findFirstFactoryByNameAndTypeOrNull<T>(instanceName, type);
assert(
instanceFactory != null,
// ignore: missing_whitespace_between_adjacent_strings
'Object/factory with ${instanceName != null ? 'with name $instanceName and ' : ' '}'
'type ${T.toString()} is not registered inside GetIt. '
'\n(Did you accidentally do GetIt sl=GetIt.instance(); instead of GetIt sl=GetIt.instance;'
'\nDid you forget to register it?)',
);
return instanceFactory;
}
/// retrieves or creates an instance of a registered type [T] depending on the registration
/// function used for this type or based on a name.
/// for factories you can pass up to 2 parameters [param1,param2] they have to match the types
/// given at registration with [registerFactoryParam()]
@override
T get<T>({String instanceName, dynamic param1, dynamic param2}) {
final instanceFactory = _findFactoryByNameAndType<T>(instanceName);
Object instance;
if (instanceFactory.isAsync || instanceFactory.pendingResult != null) {
/// We use an assert here instead of an `if..throw` for performance reasons
assert(
instanceFactory.factoryType == _ServiceFactoryType.constant ||
instanceFactory.factoryType == _ServiceFactoryType.lazy,
"You can't use get with an async Factory of ${instanceName ?? T.toString()}.");
assert(instanceFactory.isReady,
'You tried to access an instance of ${instanceName ?? T.toString()} that was not ready yet');
instance = instanceFactory.instance;
} else {
instance = instanceFactory.getObject(param1, param2);
}
assert(instance is T,
'Object with name $instanceName has a different type (${instanceFactory.registrationType.toString()}) than the one that is inferred (${T.toString()}) where you call it');
return instance as T;
}
/// Callable class so that you can write `GetIt.instance<MyType>` instead of
/// `GetIt.instance.get<MyType>`
@override
T call<T>({String instanceName, dynamic param1, dynamic param2}) {
return get<T>(instanceName: instanceName, param1: param1, param2: param2);
}
/// Returns an Future of an instance that is created by an async factory or a Singleton that is
/// not ready with its initialization.
/// for async factories you can pass up to 2 parameters [param1,param2] they have to match the types
/// given at registration with [registerFactoryParamAsync()]
@override
Future<T> getAsync<T>({String instanceName, dynamic param1, dynamic param2}) {
final factoryToGet = _findFactoryByNameAndType<T>(instanceName);
return factoryToGet.getObjectAsync<T>(param1, param2);
}
/// registers a type so that a new instance will be created on each call of [get] on that type
/// [T] type to register
/// [func] factory function for this type
/// [instanceName] if you provide a value here your factory gets registered with that
/// name instead of a type. This should only be necessary if you need to register more
/// than one instance of one type. Its highly not recommended
@override
void registerFactory<T>(FactoryFunc<T> func, {String instanceName}) {
_register<T, void, void>(
type: _ServiceFactoryType.alwaysNew,
instanceName: instanceName,
factoryFunc: func,
isAsync: false,
shouldSignalReady: false);
}
/// registers a type so that a new instance will be created on each call of [get] on that type based on
/// up to two parameters provided to [get()]
/// [T] type to register
/// [P1] type of param1
/// [P2] type of param2
/// if you use only one parameter pass void here
/// [func] factory function for this type that accepts two parameters
/// [instanceName] if you provide a value here your factory gets registered with that
/// name instead of a type. This should only be necessary if you need to register more
/// than one instance of one type. Its highly not recommended
///
/// example:
/// getIt.registerFactoryParam<TestClassParam,String,int>((s,i)
/// => TestClassParam(param1:s, param2: i));
///
/// if you only use one parameter:
///
/// getIt.registerFactoryParam<TestClassParam,String,void>((s,_)
/// => TestClassParam(param1:s);
@override
void registerFactoryParam<T, P1, P2>(FactoryFuncParam<T, P1, P2> func,
{String instanceName}) {
_register<T, P1, P2>(
type: _ServiceFactoryType.alwaysNew,
instanceName: instanceName,
factoryFuncParam: func,
isAsync: false,
shouldSignalReady: false);
}
/// We use a separate function for the async registration instead just a new parameter
/// so make the intention explicit
@override
void registerFactoryAsync<T>(FactoryFuncAsync<T> asyncFunc,
{String instanceName}) {
_register<T, void, void>(
type: _ServiceFactoryType.alwaysNew,
instanceName: instanceName,
factoryFuncAsync: asyncFunc,
isAsync: true,
shouldSignalReady: false);
}
/// registers a type so that a new instance will be created on each call of [getAsync]
/// on that type based on up to two parameters provided to [getAsync()]
/// the creation function is executed asynchronously and has to be accessed with [getAsync]
/// [T] type to register
/// [P1] type of param1
/// [P2] type of param2
/// if you use only one parameter pass void here
/// [func] factory function for this type that accepts two parameters
/// [instanceName] if you provide a value here your factory gets registered with that
/// name instead of a type. This should only be necessary if you need to register more
/// than one instance of one type. Its highly not recommended
///
/// example:
/// getIt.registerFactoryParam<TestClassParam,String,int>((s,i) async
/// => TestClassParam(param1:s, param2: i));
///
/// if you only use one parameter:
///
/// getIt.registerFactoryParam<TestClassParam,String,void>((s,_) async
/// => TestClassParam(param1:s);
@override
void registerFactoryParamAsync<T, P1, P2>(
FactoryFuncParamAsync<T, P1, P2> func,
{String instanceName}) {
_register<T, P1, P2>(
type: _ServiceFactoryType.alwaysNew,
instanceName: instanceName,
factoryFuncParamAsync: func,
isAsync: true,
shouldSignalReady: false);
}
/// registers a type as Singleton by passing a factory function that will be called
/// on the first call of [get] on that type
/// [T] type to register
/// [func] factory function for this type
/// [instanceName] if you provide a value here your factory gets registered with that
/// name instead of a type. This should only be necessary if you need to register more
/// than one instance of one type. Its highly not recommended
/// [registerLazySingleton] does not influence [allReady] however you can wait
/// for and be dependent on a LazySingleton.
@override
void registerLazySingleton<T>(FactoryFunc<T> func,
{String instanceName, DisposingFunc<T> dispose}) {
_register<T, void, void>(
type: _ServiceFactoryType.lazy,
instanceName: instanceName,
factoryFunc: func,
isAsync: false,
shouldSignalReady: false,
disposeFunc: dispose,
);
}
/// registers a type as Singleton by passing an [instance] of that type
/// that will be returned on each call of [get] on that type
/// [T] type to register
/// If [signalsReady] is set to `true` it means that the future you can get from `allReady()` cannot complete until this
/// registration was signalled ready by calling [signalsReady(instance)]
/// [instanceName] if you provide a value here your instance gets registered with that
/// name instead of a type. This should only be necessary if you need to register more
/// than one instance of one type. Its highly not recommended
@override
void registerSingleton<T>(
T instance, {
String instanceName,
bool signalsReady,
DisposingFunc<T> dispose,
}) {
_register<T, void, void>(
type: _ServiceFactoryType.constant,
instanceName: instanceName,
instance: instance,
isAsync: false,
shouldSignalReady: signalsReady ?? <T>[] is List<WillSignalReady>,
disposeFunc: dispose,
);
}
/// registers a type as Singleton by passing an factory function of that type
/// that will be called on each call of [get] on that type
/// [T] type to register
/// [instanceName] if you provide a value here your instance gets registered with that
/// name instead of a type. This should only be necessary if you need to register more
/// than one instance of one type. Its highly not recommended
/// [dependsOn] if this instance depends on other registered Singletons before it can be initialized
/// you can either orchestrate this manually using [isReady()] or pass a list of the types that the
/// instance depends on here. [factoryFunc] won't get executed till this types are ready.
/// [func] is called
/// If [signalsReady] is set to `true` it means that the future you can get from `allReady()`
/// cannot complete until this this instance was signalled ready by calling [signalsReady(instance)].
@override
void registerSingletonWithDependencies<T>(
FactoryFunc<T> providerFunc, {
String instanceName,
Iterable<Type> dependsOn,
bool signalsReady,
DisposingFunc<T> dispose,
}) {
_register<T, void, void>(
type: _ServiceFactoryType.constant,
instanceName: instanceName,
isAsync: false,
factoryFunc: providerFunc,
dependsOn: dependsOn,
shouldSignalReady: signalsReady ?? <T>[] is List<WillSignalReady>,
disposeFunc: dispose,
);
}
/// registers a type as Singleton by passing an asynchronous factory function which has to return the instance
/// that will be returned on each call of [get] on that type.
/// Therefore you have to ensure that the instance is ready before you use [get] on it or use [getAsync()] to
/// wait for the completion.
/// You can wait/check if the instance is ready by using [isReady()] and [isReadySync()].
/// [factoryfunc] is executed immediately if there are no dependencies to other Singletons (see below).
/// As soon as it returns, this instance is marked as ready unless you don't set [signalsReady==true]
/// [instanceName] if you provide a value here your instance gets registered with that
/// name instead of a type. This should only be necessary if you need to register more
/// than one instance of one type. Its highly not recommended
/// [dependsOn] if this instance depends on other registered Singletons before it can be initialized
/// you can either orchestrate this manually using [isReady()] or pass a list of the types that the
/// instance depends on here. [factoryFunc] won't get executed till this types are ready.
/// If [signalsReady] is set to `true` it means that the future you can get from `allReady()` cannot complete until this
/// this instance was signalled ready by calling [signalsReady(instance)]. In that case no automatic ready signal
/// is made after completion of [factoryfunc]
@override
void registerSingletonAsync<T>(FactoryFuncAsync<T> providerFunc,
{String instanceName,
Iterable<Type> dependsOn,
bool signalsReady,
DisposingFunc<T> dispose}) {
_register<T, void, void>(
type: _ServiceFactoryType.constant,
instanceName: instanceName,
isAsync: true,
factoryFuncAsync: providerFunc,
dependsOn: dependsOn,
shouldSignalReady: signalsReady ?? <T>[] is List<WillSignalReady>,
disposeFunc: dispose,
);
}
/// registers a type as Singleton by passing a async factory function that will be called
/// on the first call of [getAsnc] on that type
/// This is a rather esoteric requirement so you should seldom have the need to use it.
/// This factory function [providerFunc] isn't called immediately but wait till the first call by
/// [getAsync()] or [isReady()] is made
/// To control if an async Singleton has completed its [providerFunc] gets a `Completer` passed
/// as parameter that has to be completed to signal that this instance is ready.
/// Therefore you have to ensure that the instance is ready before you use [get] on it or use [getAsync()] to
/// wait for the completion.
/// You can wait/check if the instance is ready by using [isReady()] and [isReadySync()].
/// [instanceName] if you provide a value here your instance gets registered with that
/// name instead of a type. This should only be necessary if you need to register more
/// than one instance of one type. Its highly not recommended.
/// [registerLazySingletonAsync] does not influence [allReady] however you can wait
/// for and be dependent on a LazySingleton.
@override
void registerLazySingletonAsync<T>(FactoryFuncAsync<T> func,
{String instanceName, DisposingFunc<T> dispose}) {
_register<T, void, void>(
isAsync: true,
type: _ServiceFactoryType.lazy,
instanceName: instanceName,
factoryFuncAsync: func,
shouldSignalReady: false,
disposeFunc: dispose,
);
}
/// Clears all registered types. Handy when writing unit tests
@override
Future<void> reset({bool dispose = true}) async {
if (dispose) {
for (int level = _scopes.length - 1; level >= 0; level--) {
await _scopes[level].dispose();
await _scopes[level].reset(dispose: dispose);
}
}
_scopes.removeRange(1, _scopes.length);
await resetScope(dispose: dispose);
}
/// Clears all registered types of the current scope.
@override
Future<void> resetScope({bool dispose = true}) async {
if (dispose) {
await _currentScope.dispose();
}
await _currentScope.reset(dispose: dispose);
}
/// Creates a new registration scope. If you register types after creating
/// a new scope they will hide any previous registration of the same type.
/// Scopes allow you to manage different live times of your Objects.
/// [scopeName] if you name a scope you can pop all scopes above the named one
/// by using the name.
/// [dispose] function that will be called when you pop this scope. The scope
/// is still valied while it is executed
@override
void pushNewScope({String scopeName, ScopeDisposeFunc dispose}) {
assert(scopeName != _baseScopeName,
'This name is reseved for the real base scope');
assert(
_scopes.firstWhere((x) => x.name == scopeName, orElse: () => null) ==
null,
'You already have used the scope name $scopeName');
_scopes.add(_Scope(name: scopeName, disposeFunc: dispose));
}
/// Disposes all factories/Singletons that have ben registered in this scope
/// and pops (destroys) the scope so that the previous scope gets active again.
/// if you provided dispose functions on registration, they will be called.
/// if you passed a dispose function when you pushed this scope it will be
/// calles before the scope is popped.
/// As dispose funcions can be async, you should await this function.
@override
Future<void> popScope() async {
assert(
_scopes.length > 1,
"You are already on the base scope. you can't pop"
' this one');
await _currentScope.dispose();
await _currentScope.reset(dispose: true);
_scopes.removeLast();
}
/// if you have a lot of scopes with names you can pop (see [popScope]) all scopes above
/// the scope with [scopeName] including that scope
/// Scopes are poped in order from the top
/// As dispose funcions can be async, you should await this function.
@override
Future<bool> popScopesTill(String scopeName) async {
assert(scopeName != _baseScopeName, "You can't pop the base scope");
if (_scopes.firstWhere((x) => x.name == scopeName, orElse: () => null) ==
null) {
return false;
}
String _scopeName;
do {
_scopeName = _currentScope.name;
await popScope();
} while (_scopeName != scopeName);
return true;
}
void _register<T, P1, P2>(
{@required _ServiceFactoryType type,
FactoryFunc<T> factoryFunc,
FactoryFuncParam<T, P1, P2> factoryFuncParam,
FactoryFuncAsync<T> factoryFuncAsync,
FactoryFuncParamAsync<T, P1, P2> factoryFuncParamAsync,
T instance,
@required String instanceName,
@required bool isAsync,
Iterable<Type> dependsOn,
@required bool shouldSignalReady,
DisposingFunc<T> disposeFunc}) {
throwIfNot(
const Object() is! T,
'GetIt: You have to provide type. Did you accidentally do `var sl=GetIt.instance();` instead of var sl=GetIt.instance;',
);
final factoriesByName = _currentScope.factoriesByName;
throwIf(
factoriesByName.containsKey(instanceName) &&
factoriesByName[instanceName].containsKey(T) &&
!allowReassignment,
ArgumentError(
'Object/factory with ${instanceName != null ? 'with name $instanceName and ' : ''}'
' type ${T.toString()} is already registered inside GetIt. '));
final serviceFactory = _ServiceFactory<T, P1, P2>(type,
creationFunction: factoryFunc,
creationFunctionParam: factoryFuncParam,
asyncCreationFunctionParam: factoryFuncParamAsync,
asyncCreationFunction: factoryFuncAsync,
instance: instance,
isAsync: isAsync,
instanceName: instanceName,
shouldSignalReady: shouldSignalReady,
disposeFunction: disposeFunc);
factoriesByName.putIfAbsent(instanceName,
() => <Type, _ServiceFactory<dynamic, dynamic, dynamic>>{});
factoriesByName[instanceName][T] = serviceFactory;
// simple Singletons get creates immediately
if (type == _ServiceFactoryType.constant &&
!shouldSignalReady &&
!isAsync &&
(dependsOn?.isEmpty ?? false)) {
serviceFactory.instance = factoryFunc();
serviceFactory._readyCompleter.complete();
return;
}
// if its an async or an dependent Singleton we start its creation function here after we check if
// it is dependent on other registered Singletons.
if ((isAsync || (dependsOn?.isNotEmpty ?? false)) &&
type == _ServiceFactoryType.constant) {
/// Any client awaiting the completion of this Singleton
/// Has to wait for the completion of the Singleton itself as well
/// as for the completion of all the Singletons this one depends on
/// For this we use [outerFutureGroup]
/// A `FutureGroup` completes only if it's closed and all contained
/// Futures have completed
final outerFutureGroup = FutureGroup();
Future dependentFuture;
if (dependsOn?.isNotEmpty ?? false) {
/// To wait for the completion of all Singletons this one is depending on
/// before we start to create itself we use [dependentFutureGroup]
final dependentFutureGroup = FutureGroup();
for (final type in dependsOn) {
final dependentFactory =
_findFirstFactoryByNameAndTypeOrNull(null, type);
throwIf(dependentFactory == null,
ArgumentError('Dependent Type $type is not registered in GetIt'));
throwIfNot(dependentFactory.canBeWaitedFor,
ArgumentError('Dependent Type $type is not an async Singleton'));
dependentFactory.objectsWaiting.add(serviceFactory.registrationType);
dependentFutureGroup.add(dependentFactory._readyCompleter.future);
}
dependentFutureGroup.close();
dependentFuture = dependentFutureGroup.future;
} else {
/// if we have no dependencies we still create a dummy Future so that
/// we can use the same code path further down
dependentFuture = Future.sync(() {}); // directly execute then
}
outerFutureGroup.add(dependentFuture);
/// if someone uses getAsync on an async Singleton that has not be started to get created
/// because its dependent on other objects this doesn't work because [pendingResult] is not set in
/// that case. Therefore we have to set [outerFutureGroup] as [pendingResult]
dependentFuture.then((_) {
Future<T> isReadyFuture;
if (!isAsync) {
/// SingletonWithDepencencies
serviceFactory.instance = factoryFunc();
isReadyFuture = Future<T>.value(serviceFactory.instance as T);
if (!serviceFactory.shouldSignalReady) {
/// As this isn't an asnc function we declare it as ready here
/// if is wasn't marked that it will signalReady
serviceFactory._readyCompleter.complete();
}
} else {
/// Async Singleton with dependencies
final asyncResult = factoryFuncAsync();
isReadyFuture = asyncResult.then((instance) {
serviceFactory.instance = instance;
if (!serviceFactory.shouldSignalReady && !serviceFactory.isReady) {
serviceFactory._readyCompleter.complete();
}
return instance;
});
}
outerFutureGroup.add(isReadyFuture);
outerFutureGroup.close();
});
/// outerFutureGroup.future returns a Future<List> and not a Future<T>
/// As we know that the actual factory function was added last to the FutureGroup
/// we just use that one
serviceFactory.pendingResult =
outerFutureGroup.future.then((completedFutures) {
return completedFutures.last as T;
});
}
}
/// Tests if an [instance] of an object or aType [T] or a name [instanceName]
/// is registered inside GetIt
@override
bool isRegistered<T extends Object>({
Object instance,
String instanceName,
}) {
if (instance != null) {
return _findFirstFactoryByInstanceOrNull(instance) != null;
} else {
return _findFirstFactoryByNameAndTypeOrNull<T>(instanceName) != null;
}
}
/// Unregister an instance of an object or a factory/singleton by Type [T] or by name [instanceName]
/// if you need to dispose any resources you can do it using [disposingFunction] function
/// that provides a instance of your class to be disposed
@override
void unregister<T>(
{Object instance,
String instanceName,
void Function(T) disposingFunction}) {
_ServiceFactory factoryToRemove;
if (instance != null) {
factoryToRemove = _findFactoryByInstance(instance);
} else {
factoryToRemove = _findFactoryByNameAndType<T>(instanceName);
}
throwIf(
factoryToRemove.objectsWaiting.isNotEmpty,
StateError(
'There are still other objects waiting for this instance so signal ready'));
_currentScope.factoriesByName[factoryToRemove.instanceName]
.remove(factoryToRemove.registrationType);
if (factoryToRemove.instance != null) {
if (disposingFunction != null) {
disposingFunction?.call(factoryToRemove.instance as T);
} else {
factoryToRemove.dispose();
}
}
}
/// Clears the instance of a lazy singleton,
/// being able to call the factory function on the next call
/// of [get] on that type again.
/// you select the lazy Singleton you want to reset by either providing
/// an [instance], its registered type [T] or its registration name.
/// if you need to dispose some resources before the reset, you can
/// provide a [disposingFunction]
@override
void resetLazySingleton<T>(
{Object instance,
String instanceName,
void Function(T) disposingFunction}) {
_ServiceFactory factoryToReset;
if (instance != null) {
factoryToReset = _findFactoryByInstance(instance);
} else {
factoryToReset = _findFactoryByNameAndType<T>(instanceName);
}
throwIfNot(
factoryToReset.factoryType == _ServiceFactoryType.lazy,
StateError(
'There is no type ${instance.runtimeType} registered as LazySingleton in GetIt'));
if (factoryToReset.instance != null) {
if (disposingFunction != null) {
disposingFunction?.call(factoryToReset.instance as T);
} else {
factoryToReset.dispose();
}
}
factoryToReset.instance = null;
factoryToReset.pendingResult = null;
factoryToReset._readyCompleter = Completer();
}
List<_ServiceFactory> get _allFactories => _scopes
.fold<List<_ServiceFactory>>([], (sum, x) => sum..addAll(x.allFactories));
_ServiceFactory _findFirstFactoryByInstanceOrNull(Object instance) {
final registeredFactories =
_allFactories.where((x) => identical(x.instance, instance));
return registeredFactories.isEmpty ? null : registeredFactories.first;
}
_ServiceFactory _findFactoryByInstance(Object instance) {
final registeredFactory = _findFirstFactoryByInstanceOrNull(instance);
throwIf(
registeredFactory == null,
StateError(
'This instance of the type ${instance.runtimeType} is not available in GetIt '
'If you have registered it as LazySingleton, are you sure you have used '
'it at least once?'),
);
return registeredFactory;
}
/// Used to manually signal the ready state of a Singleton.
/// If you want to use this mechanism you have to pass [signalsReady==true] when registering
/// the Singleton.
/// If [instance] has a value GetIt will search for the responsible Singleton
/// and completes all futures that might be waited for by [isReady]
/// If all waiting singletons have signalled ready the future you can get
/// from [allReady] is automatically completed
///
/// Typically this is used in this way inside the registered objects init
/// method `GetIt.instance.signalReady(this);`
///
/// if [instance] is `null` and no factory/singleton is waiting to be signalled this
/// will complete the future you got from [allReady], so it can be used to globally
/// giving a ready Signal
///
/// Both ways are mutual exclusive, meaning either only use the global `signalReady()` and
/// don't register a singleton to signal ready or use any async registrations
///
/// Or use async registrations methods or let individual instances signal their ready
/// state on their own.
@override
void signalReady(Object instance) {
_ServiceFactory registeredInstance;
if (instance != null) {
registeredInstance = _findFactoryByInstance(instance);
throwIf(
registeredInstance == null,
ArgumentError.value(instance,
'There is no object type ${instance.runtimeType} registered in GetIt'));
throwIfNot(
registeredInstance.shouldSignalReady,
ArgumentError.value(instance,
'This instance of type ${instance.runtimeType} is not supposed to be signalled.\nDid you forget to set signalsReady==true when registering it?'));
throwIf(
registeredInstance.isReady,
StateError(
'This instance of type ${instance.runtimeType} was already signalled'));
registeredInstance._readyCompleter.complete();
registeredInstance.objectsWaiting.clear();
} else {
/// Manual signalReady without an instance
/// In case that there are still factories that are marked to wait for a signal
/// but aren't signalled we throw an error with details which objects are concerned
final notReady = _allFactories
.where((x) =>
(x.shouldSignalReady) && (!x.isReady) ||
(x.pendingResult != null) && (!x.isReady))
.map<String>((x) => '${x.registrationType}/${x.instanceName}')
.toList();
throwIf(
notReady.isNotEmpty,
StateError(
"You can't signal ready manually if you have registered instances that should signal ready or are asnyc.\n"
// this lint is stupif because it doesn't recognize newlines
// ignore: missing_whitespace_between_adjacent_strings
'Did you forget to pass an object instance?'
'This registered types/names: $notReady should signal ready but are not ready'));
_globalReadyCompleter.complete();
}
}
/// returns a Future that completes if all asynchronously created Singletons and any Singleton that had
/// [signalsReady==true] are ready.
/// This can be used inside a FutureBuilder to change the UI as soon as all initialization
/// is done
/// If you pass a [timeout], an [WaitingTimeOutException] will be thrown if not all Singletons
/// were ready in the given time. The Exception contains details on which Singletons are not ready yet.
@override
Future<void> allReady(
{Duration timeout, bool ignorePendingAsyncCreation = false}) {
final futures = FutureGroup();
_allFactories
.where((x) =>
(x.isAsync && !ignorePendingAsyncCreation ||
(!x.isAsync &&
x.pendingResult != null) || // Singletons with dependencies
x.shouldSignalReady) &&
!x.isReady &&
x.factoryType == _ServiceFactoryType.constant)
.forEach((f) {
futures.add(f._readyCompleter.future);
});
futures.close();
if (timeout != null) {
return futures.future.timeout(timeout, onTimeout: _throwTimeoutError);
} else {
return futures.future;
}
}
/// Returns if all async Singletons are ready without waiting
/// if [allReady] should not wait for the completion of async Signletons set
/// [ignorePendingAsyncCreation==true]
@override
bool allReadySync([bool ignorePendingAsyncCreation = false]) {
final notReadyTypes = _allFactories
.where((x) =>
(x.isAsync && !ignorePendingAsyncCreation ||
(!x.isAsync &&
x.pendingResult !=
null) || // Singletons with dependencies
x.shouldSignalReady) &&
!x.isReady &&
x.factoryType == _ServiceFactoryType.constant ||
x.factoryType == _ServiceFactoryType.lazy)
.map<String>((x) {
if (x.isNamedRegistration) {
return 'Object ${x.instanceName} has not completed';
} else {
return 'Registered object of Type ${x.registrationType.toString()} has not completed';
}
}).toList();
/// IN debug mode we print the List of not ready types/named instances
if (notReadyTypes.isNotEmpty) {
// Hack to only output this in debug mode;
assert(() {
// ignore: avoid_print
print('Not yet ready objects:');
// ignore: avoid_print
print(notReadyTypes);
return true;
}());
}
return notReadyTypes.isEmpty;
}
/// we use dynamic here because this functoin is used at two places, one that expects a Future
/// the other a List. As this function just throws an exception and doesn't return anything
/// this is save
List _throwTimeoutError() {
final allFactories = _allFactories;
final waitedBy = Map.fromEntries(
allFactories
.where((x) =>
(x.shouldSignalReady || x.pendingResult != null) &&
!x.isReady &&
x.objectsWaiting.isNotEmpty)
.map<MapEntry<String, List<String>>>(
(isWaitedFor) => MapEntry(
isWaitedFor.debugName,
isWaitedFor.objectsWaiting
.map((waitedByType) => waitedByType.toString())
.toList()),
),
);
final notReady = allFactories
.where((x) =>
(x.shouldSignalReady || x.pendingResult != null) && !x.isReady)
.map((f) => f.debugName)
.toList();
final areReady = allFactories
.where((x) =>
(x.shouldSignalReady || x.pendingResult != null) && x.isReady)
.map((f) => f.debugName)
.toList();
throw WaitingTimeOutException(waitedBy, notReady, areReady);
}
/// Returns a Future that completes if the instance of an Singleton, defined by Type [T] or
/// by name [instanceName] or by passing the an existing [instance], is ready
/// If you pass a [timeout], an [WaitingTimeOutException] will be thrown if the instance
/// is not ready in the given time. The Exception contains details on which Singletons are
/// not ready at that time.
/// [callee] optional parameter which makes debugging easier. Pass `this` in here.
@override
Future<void> isReady<T>({
Object instance,
String instanceName,
Duration timeout,
Object callee,
}) {
_ServiceFactory factoryToCheck;
if (instance != null) {
factoryToCheck = _findFactoryByInstance(instance);
} else {
factoryToCheck = _findFactoryByNameAndType<T>(instanceName);
}
throwIfNot(
factoryToCheck.canBeWaitedFor &&
factoryToCheck.factoryType != _ServiceFactoryType.alwaysNew,
ArgumentError(
'You only can use this function on Singletons that are async, that are marked as dependen '
'or that are marked with "signalsReady==true"'),
);
factoryToCheck.objectsWaiting.add(callee.runtimeType);
if (factoryToCheck.isAsync &&
factoryToCheck.factoryType == _ServiceFactoryType.lazy &&
factoryToCheck.instance == null) {
if (timeout != null) {
return factoryToCheck.getObjectAsync(null, null).timeout(timeout,
onTimeout: () {
_throwTimeoutError();
return null;
});
} else {
return factoryToCheck.getObjectAsync(null, null);
}
}
if (timeout != null) {
return factoryToCheck._readyCompleter.future
.timeout(timeout, onTimeout: _throwTimeoutError);
} else {
return factoryToCheck._readyCompleter.future;
}
}
/// Checks if an async Singleton defined by an [instance], a type [T] or an [instanceName]
/// is ready without waiting.
@override
bool isReadySync<T>({Object instance, String instanceName}) {
_ServiceFactory factoryToCheck;
if (instance != null) {
factoryToCheck = _findFactoryByInstance(instance);
} else {
factoryToCheck = _findFactoryByNameAndType<T>(instanceName);
}
throwIfNot(
factoryToCheck.canBeWaitedFor &&
factoryToCheck.factoryType != _ServiceFactoryType.alwaysNew,
ArgumentError(
'You only can use this function on async Singletons or Singletons '
'that have ben marked with "signalsReady" or that they depend on others'));
return factoryToCheck.isReady;
}
}
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/log/log_utils.dart | Dart |
/// 这个使用flutter日志打印
class LogUtils {
static const String _defTag = 'FlutterLogUtils';
//是否是debug模式,true: log v 不输出.
static bool _debugMode = true;
static int _maxLen = 128;
static String _tagValue = _defTag;
static void init({
String tag = _defTag,
bool isDebug = false,
int maxLen = 128,
}) {
_tagValue = tag;
_debugMode = isDebug;
_maxLen = maxLen;
}
///打印debug日志
static void d(Object object, {String tag}) {
if (_debugMode) {
_printLog(tag,' d ', object);
}
}
///打印error日志
static void e(Object object, {String tag}) {
_printLog(tag, ' e ', object);
}
///打印v日志
static void v(Object object, {String tag}) {
if (_debugMode) {
_printLog(tag, ' v ', object);
}
}
///打印info日志
static void i(Object object, {String tag}) {
if (_debugMode) {
_printLog(tag, ' i ', object);
}
}
///打印ware警告日志
static void w(Object object, {String tag}) {
if (_debugMode) {
_printLog(tag, ' w ', object);
}
}
static void _printLog(String tag, String stag, Object object) {
String da = object?.toString() ?? 'null';
if(tag == null || tag.isEmpty){
tag = _tagValue;
}
if (da.length <= _maxLen) {
print('$tag$stag $da');
return;
}
print('$tag$stag — — — — — — — — — — st — — — — — — — — — — — — —');
while (da.isNotEmpty) {
if (da.length > _maxLen) {
print('$tag$stag| ${da.substring(0, _maxLen)}');
da = da.substring(_maxLen, da.length);
} else {
print('$tag$stag| $da');
da = '';
}
}
print('$tag$stag — — — — — — — — — — ed — — — — — — — — — ---— —');
}
}
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/net/base_respond.dart | Dart | /*
Copyright 2017 yangchong211(github.com/yangchong211)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
* <pre>
* @author yangchong
* blog : https://github.com/yangchong211
* time : 2018/9/12
* desc : 返回数据
* revise:
* </pre>
*/
class BaseRespond {
/*
返回数据结构如下所示
{
"data": ...,
"errorCode": 0,
"errorMsg": ""
}
*/
int errorCode;
String errorMsg;
var data;
} | yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/net/http_api_utils.dart | Dart | /*
Copyright 2017 yangchong211(github.com/yangchong211)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'dart:async';
import 'package:yc_flutter_utils/net/http_request.dart';
///网络请求工具类
class HttpUtils{
static const String GET = "get";
static const String POST = "post";
static String BASE_URL = "";
static void setBaseUrl(String baseUrl){
BASE_URL = baseUrl;
}
//get请求
static void get(String url, Function callback, {Map<String, String> params,
Map<String, String> headers, Function errorCallback}) async {
if (!url.startsWith("http")) {
url = BASE_URL + url;
}
//做非空判断
if (params != null && params.isNotEmpty) {
StringBuffer sb = new StringBuffer("?");
params.forEach((key, value) {
sb.write("$key" + "=" + "$value" + "&");
});
String paramStr = sb.toString();
paramStr = paramStr.substring(0, paramStr.length - 1);
url += paramStr;
}
await HttpRequest.startRequest(url, callback, method: GET, headers: headers,
errorCallback: errorCallback);
}
//post请求
static void post(String url, Function callback, {Map<String, String> params,
Map<String, String> headers, Function errorCallback}) async {
if (!url.startsWith("http")) {
url = BASE_URL + url;
}
await HttpRequest.startRequest(url, callback, method: POST,
headers: headers, params: params, errorCallback: errorCallback);
}
}
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/net/http_request.dart | Dart |
import 'dart:convert';
import 'dart:io';
import 'package:http/http.dart' as http;
import 'dart:async';
import 'package:yc_flutter_utils/log/log_utils.dart';
import 'package:yc_flutter_utils/net/http_api_utils.dart';
///网络请求工具类
class HttpRequest{
///开始网络请求
static Future startRequest(String url, Function callback, {String method,
Map<String, String> headers, Map<String, String> params,
Function errorCallback}) async {
//暂时先用这个,后期看能否抽取成model
String errorMsg;
int errorCode;
var data;
try {
//这个是请求头参数
Map<String, String> headerMap = headers == null ? new Map() : headers;
//这个是请求参数
Map<String, String> paramMap = params == null ? new Map() : params;
http.Response res;
if (HttpUtils.POST == method) {
LogUtils.i("POST:URL="+url);
LogUtils.i("POST:BODY="+paramMap.toString());
//post请求
res = await http.post(url, headers: headerMap, body: paramMap);
} else {
LogUtils.i("GET:URL="+url);
//get请求
res = await http.get(url, headers: headerMap);
}
/*if(res.statusCode < 200 || res.statusCode >= 300) {
errorMsg = "网络请求错误,状态码:" + res.statusCode.toString();
handError(errorCallback, errorMsg);
return;
}*/
if (res.statusCode != 200) {
errorMsg = "网络请求错误,状态码:" + res.statusCode.toString();
handError(errorCallback, errorMsg);
return;
}
//以下部分可以根据自己业务需求封装,这里是errorCode>=0则为请求成功,data里的是数据部分
//记得Map中的泛型为dynamic
//这个是相应body
var body = res.body;
Map<String, dynamic> map = json.decode(body);
errorCode = map['errorCode'];
errorMsg = map['errorMsg'];
data = map['data'];
//callback返回data,数据类型为dynamic
//errorCallback中为了方便我直接返回了String类型的errorMsg
if (callback != null) {
if (errorCode >= 0) {
callback(data);
} else {
handError(errorCallback, errorMsg);
}
}
} catch (exception) {
handError(errorCallback, exception.toString());
}
}
static void handError(Function errorCallback,String errorMsg){
if (errorCallback != null) {
errorCallback(errorMsg);
}
LogUtils.e("errorMsg :"+errorMsg);
}
}
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/net/http_request_client.dart | Dart |
import 'dart:convert';
import 'dart:io';
import 'package:yc_flutter_utils/log/log_utils.dart';
import 'package:yc_flutter_utils/net/http_api_utils.dart';
class HttpRequestClient {
///开始网络请求
static Future startRequest(String url, Function callback, {String method,
Map<String, String> headers, Map<String, String> params,
Function errorCallback}) async {
//暂时先用这个,后期看能否抽取成model
String errorMsg;
int errorCode;
var data;
//创建一个HttpClient
HttpClient httpClient = new HttpClient();
try {
//这个是请求头参数
Map<String, String> headerMap = headers == null ? new Map() : headers;
//这个是请求参数
Map<String, String> paramMap = params == null ? new Map() : params;
HttpClientRequest request;
//打开Http连接
if (HttpUtils.POST == method) {
LogUtils.i("POST:URL="+url);
LogUtils.i("POST:BODY="+paramMap.toString());
//post请求
request = await httpClient.postUrl(Uri.parse(url));
} else {
LogUtils.i("GET:URL="+url);
//get请求
request = await httpClient.getUrl(Uri.parse(url));
}
//添加请求头
HttpHeaders reqHeaders = request.headers;
if(headerMap!=null && headerMap.length>0){
for(int i=0 ; i<headerMap.length ; i++){
var key = headerMap[i];
reqHeaders.add(key, headerMap[key]);
}
}
//等待连接服务器(会将请求信息发送给服务器)
HttpClientResponse response = await request.close();
/*if(res.statusCode < 200 || res.statusCode >= 300) {
errorMsg = "网络请求错误,状态码:" + res.statusCode.toString();
handError(errorCallback, errorMsg);
return;
}*/
if (response.statusCode != 200) {
errorMsg = "网络请求错误,状态码:" + response.statusCode.toString();
handError(errorCallback, errorMsg);
return;
}
//以下部分可以根据自己业务需求封装,这里是errorCode>=0则为请求成功,data里的是数据部分
//记得Map中的泛型为dynamic
//这个是相应body
//读取响应内容
var body = await response.transform(utf8.decoder).join();
Map<String, dynamic> map = json.decode(body);
errorCode = map['errorCode'];
errorMsg = map['errorMsg'];
data = map['data'];
//callback返回data,数据类型为dynamic
//errorCallback中为了方便我直接返回了String类型的errorMsg
if (callback != null) {
if (errorCode >= 0) {
callback(data);
} else {
handError(errorCallback, errorMsg);
}
}
//关闭client后,通过该client发起的所有请求都会中止。
//httpClient.close();
} catch (exception) {
handError(errorCallback, exception.toString());
}
}
static void handError(Function errorCallback,String errorMsg){
if (errorCallback != null) {
errorCallback(errorMsg);
}
LogUtils.e("errorMsg :"+errorMsg);
}
} | yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/net/url_utils.dart | Dart |
import 'package:yc_flutter_utils/flutter_utils.dart';
class UrlUtils{
/// 返回输入是否匹配url的正则表达式。
static bool isURL(String url) {
if(TextUtils.isEmpty(url)){
return false;
}
return RegexUtils.matches(RegexConstants.REGEX_URL, url);
}
/// 获取url链接中host
static String getUrlHost(String url){
if(TextUtils.isEmpty(url)){
return null;
}
String host ;
try{
host = Uri.parse(url).host;
} catch(e){
host = null;
}
return host;
}
/// 获取url链接中scheme
static String getUrlScheme(String url){
if(TextUtils.isEmpty(url)){
return null;
}
String host ;
try{
host = Uri.parse(url).scheme;
} catch(e){
host = null;
}
return host;
}
/// 判断url链接是否包含参数
static bool containsTarget(String url, String target) {
if (TextUtils.isNotEmpty(url)) {
Uri uri = Uri.parse(url);
for (int i = 0; i < uri.pathSegments.length; i++) {
if (uri.pathSegments[i] == target) {
return true;
}
}
}
return false;
}
/// 获取url中第一个参数
static String getFirstPath(String url) {
if(TextUtils.isEmpty(url)){
return null;
}
Uri uri = Uri.tryParse(url);
if(ObjectUtils.isEmpty(uri)){
return null;
}
if (uri.queryParameters.length > 0) {
uri = uri.replace(queryParameters: Map());
}
return uri.pathSegments[0];
}
} | yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/num/decimal.dart | Dart |
import 'package:yc_flutter_utils/num/rational.dart';
class Decimal implements Comparable<Decimal> {
factory Decimal.parse(String value) =>
Decimal._fromRational(Rational.parse(value));
factory Decimal.fromInt(int value) =>
Decimal._fromRational(Rational(BigInt.from(value)));
Decimal._fromRational(this._rational);
static Decimal zero = Decimal.fromInt(0);
static Decimal one = Decimal.fromInt(1);
static Decimal tryParse(String value) {
try {
return Decimal.parse(value);
} on FormatException {
return null;
}
}
Rational _rational;
bool get isInteger => _rational.isInteger;
Decimal get inverse => Decimal._fromRational(_rational.inverse);
@override
bool operator ==(Object other) =>
other is Decimal && _rational == other._rational;
@override
int get hashCode => _rational.hashCode;
@override
String toString() => _rational.toDecimalString();
// implementation of Comparable
@override
int compareTo(Decimal other) => _rational.compareTo(other._rational);
// implementation of num
Decimal operator +(Decimal other) =>
Decimal._fromRational(_rational + other._rational);
Decimal operator -(Decimal other) =>
Decimal._fromRational(_rational - other._rational);
Decimal operator *(Decimal other) =>
Decimal._fromRational(_rational * other._rational);
Decimal operator %(Decimal other) =>
Decimal._fromRational(_rational % other._rational);
Decimal operator /(Decimal other) =>
Decimal._fromRational(_rational / other._rational);
/// Truncating division operator.
///
/// The result of the truncating division [:a ~/ b:] is equivalent to
/// [:(a / b).truncate():].
Decimal operator ~/(Decimal other) =>
Decimal._fromRational(_rational ~/ other._rational);
Decimal operator -() => Decimal._fromRational(-_rational);
/// Return the remainder from dividing this [num] by [other].
Decimal remainder(Decimal other) =>
Decimal._fromRational(_rational.remainder(other._rational));
/// Relational less than operator.
bool operator <(Decimal other) => _rational < other._rational;
/// Relational less than or equal operator.
bool operator <=(Decimal other) => _rational <= other._rational;
/// Relational greater than operator.
bool operator >(Decimal other) => _rational > other._rational;
/// Relational greater than or equal operator.
bool operator >=(Decimal other) => _rational >= other._rational;
bool get isNaN => _rational.isNaN;
bool get isNegative => _rational.isNegative;
bool get isInfinite => _rational.isInfinite;
/// Returns the absolute value of this [num].
Decimal abs() => Decimal._fromRational(_rational.abs());
/// The signum function value of this [num].
///
/// E.e. -1, 0 or 1 as the value of this [num] is negative, zero or positive.
int get signum => _rational.signum;
/// Returns the greatest integer value no greater than this [num].
Decimal floor() => Decimal._fromRational(_rational.floor());
/// Returns the least integer value that is no smaller than this [num].
Decimal ceil() => Decimal._fromRational(_rational.ceil());
/// Returns the integer value closest to this [num].
///
/// Rounds away from zero when there is no closest integer:
/// [:(3.5).round() == 4:] and [:(-3.5).round() == -4:].
Decimal round() => Decimal._fromRational(_rational.round());
/// Returns the integer value obtained by discarding any fractional digits
/// from this [num].
Decimal truncate() => Decimal._fromRational(_rational.truncate());
/// Returns the integer value closest to `this`.
///
/// Rounds away from zero when there is no closest integer:
/// [:(3.5).round() == 4:] and [:(-3.5).round() == -4:].
///
/// The result is a double.
double roundToDouble() => _rational.roundToDouble();
/// Returns the greatest integer value no greater than `this`.
///
/// The result is a double.
double floorToDouble() => _rational.floorToDouble();
/// Returns the least integer value no smaller than `this`.
///
/// The result is a double.
double ceilToDouble() => _rational.ceilToDouble();
/// Returns the integer obtained by discarding any fractional digits from
/// `this`.
///
/// The result is a double.
double truncateToDouble() => _rational.truncateToDouble();
/// Clamps `this` to be in the range [lowerLimit]-[upperLimit]. The comparison
/// is done using [compareTo] and therefore takes [:-0.0:] into account.
Decimal clamp(Decimal lowerLimit, Decimal upperLimit) =>
Decimal._fromRational(
_rational.clamp(lowerLimit._rational, upperLimit._rational));
/// Truncates this [num] to an integer and returns the result as an [int].
int toInt() => _rational.toInt();
/// Return this [num] as a [double].
///
/// If the number is not representable as a [double], an approximation is
/// returned. For numerically large integers, the approximation may be
/// infinite.
double toDouble() => _rational.toDouble();
/// Inspect if this [num] has a finite precision.
bool get hasFinitePrecision => _rational.hasFinitePrecision;
/// The precision of this [num].
///
/// The sum of the number of digits before and after the decimal point.
///
/// Throws [StateError] if the precision is infinite, i.e. when
/// [hasFinitePrecision] is `false`.
int get precision => _rational.precision;
/// The scale of this [num].
///
/// The number of digits after the decimal point.
///
/// Throws [StateError] if the scale is infinite, i.e. when
/// [hasFinitePrecision] is `false`.
int get scale => _rational.scale;
/// Converts a [num] to a string representation with [fractionDigits] digits
/// after the decimal point.
String toStringAsFixed(int fractionDigits) =>
_rational.toStringAsFixed(fractionDigits);
/// Converts a [num] to a string in decimal exponential notation with
/// [fractionDigits] digits after the decimal point.
String toStringAsExponential([int fractionDigits]) =>
_rational.toStringAsExponential(fractionDigits);
/// Converts a [num] to a string representation with [precision] significant
/// digits.
String toStringAsPrecision(int precision) =>
_rational.toStringAsPrecision(precision);
/// Returns `this` to the power of [exponent].
///
/// Returns [one] if the [exponent] equals `0`.
///
/// The [exponent] must otherwise be positive.
Decimal pow(int exponent) => Decimal._fromRational(_rational.pow(exponent));
}
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/num/money_format.dart | Dart |
enum MoneyFormat {
NORMAL, //保留两位小数(6.00元)
END_INTEGER, //去掉末尾'0'(6.00元 -> 6元, 6.60元 -> 6.6元)
YUAN_INTEGER, //整元(6.00元 -> 6元)
}
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/num/money_unit.dart | Dart |
enum MoneyUnit {
NORMAL, // 6.00
YUAN, // ¥6.00
YUAN_ZH, // 6.00元
DOLLAR, // $6.00
} | yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/num/money_utils.dart | Dart |
import 'package:yc_flutter_utils/num/money_format.dart';
import 'package:yc_flutter_utils/num/money_unit.dart';
import 'package:yc_flutter_utils/num/num_utils.dart';
/// Money Util.
class MoneyUtils {
static const String YUAN = '¥';
static const String YUAN_ZH = '元';
static const String DOLLAR = '\$';
/// fen to yuan, format output.
/// 分 转 元, format格式输出.
static String changeF2Y(int amount,
{MoneyFormat format = MoneyFormat.NORMAL}) {
String moneyTxt;
double yuan = NumUtils.divideNum(amount, 100);
switch (format) {
case MoneyFormat.NORMAL:
moneyTxt = yuan.toStringAsFixed(2);
break;
case MoneyFormat.END_INTEGER:
if (amount % 100 == 0) {
moneyTxt = yuan.toInt().toString();
} else if (amount % 10 == 0) {
moneyTxt = yuan.toStringAsFixed(1);
} else {
moneyTxt = yuan.toStringAsFixed(2);
}
break;
case MoneyFormat.YUAN_INTEGER:
moneyTxt = (amount % 100 == 0)
? yuan.toInt().toString()
: yuan.toStringAsFixed(2);
break;
}
return moneyTxt;
}
/// fen str to yuan, format & unit output.
/// 分字符串 转 元, format 与 unit 格式 输出.
static String changeFStr2YWithUnit(String amountStr,
{MoneyFormat format = MoneyFormat.NORMAL,
MoneyUnit unit = MoneyUnit.NORMAL}) {
int amount = int.parse(amountStr);
return changeF2YWithUnit(amount, format: format, unit: unit);
}
/// fen to yuan, format & unit output.
/// 分 转 元, format 与 unit 格式 输出.
static String changeF2YWithUnit(int amount,
{MoneyFormat format = MoneyFormat.NORMAL,
MoneyUnit unit = MoneyUnit.NORMAL}) {
return withUnit(changeF2Y(amount, format: format), unit);
}
/// yuan, format & unit output.(yuan is int,double,str).
/// 元, format 与 unit 格式 输出.
static String changeYWithUnit(Object yuan, MoneyUnit unit,
{MoneyFormat format}) {
String yuanTxt = yuan.toString();
if (format != null) {
int amount = changeY2F(yuan);
yuanTxt = changeF2Y(amount.toInt(), format: format);
}
return withUnit(yuanTxt, unit);
}
/// yuan to fen.
/// 元 转 分,
static int changeY2F(Object yuan) {
return NumUtils.multiplyDecString(yuan.toString(), '100').toInt();
}
/// with unit.
/// 拼接单位.
static String withUnit(String moneyTxt, MoneyUnit unit) {
switch (unit) {
case MoneyUnit.YUAN:
moneyTxt = YUAN + moneyTxt;
break;
case MoneyUnit.YUAN_ZH:
moneyTxt = moneyTxt + YUAN_ZH;
break;
case MoneyUnit.DOLLAR:
moneyTxt = DOLLAR + moneyTxt;
break;
default:
break;
}
return moneyTxt;
}
}
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/num/num_utils.dart | Dart |
import 'package:yc_flutter_utils/num/decimal.dart';
import 'package:yc_flutter_utils/object/object_utils.dart';
/// num工具类
class NumUtils {
/// Checks if string is int or double.
/// 检查字符串是int还是double
static bool isNum(String s) {
if (ObjectUtils.isNull(s)){
return false;
}
return num.tryParse(s) is num ?? false;
}
/// 将数字字符串转num,数字保留x位小数
static num getNumByValueString(String valueStr, {int fractionDigits}) {
double value = double.tryParse(valueStr);
return fractionDigits == null ? value
: getNumByValueDouble(value, fractionDigits);
}
/// 浮点数字保留x位小数
static num getNumByValueDouble(double value, int fractionDigits) {
if (value == null) return null;
String valueStr = value.toStringAsFixed(fractionDigits);
return fractionDigits == 0
? int.tryParse(valueStr)
: double.tryParse(valueStr);
}
/// get int by value string
/// 将数字字符串转int
static int getIntByValueString(String valueStr, {int defValue = 0}) {
return int.tryParse(valueStr) ?? defValue;
}
/// get double by value str.
/// 数字字符串转double
static double getDoubleByValueString(String valueStr, {double defValue = 0}) {
return double.tryParse(valueStr) ?? defValue;
}
/// isZero
/// 判断是否是否是0
static bool isZero(num value) {
return value == null || value == 0;
}
/// add (without loosing precision).
/// 两个数相加(防止精度丢失)
static double addNum(num a, num b) {
return addDec(a, b).toDouble();
}
/// subtract (without loosing precision).
/// 两个数相减(防止精度丢失)
static double subtractNum(num a, num b) {
return subtractDec(a, b).toDouble();
}
/// multiply (without loosing precision).
/// 两个数相乘(防止精度丢失)
static double multiplyNum(num a, num b) {
return multiplyDec(a, b).toDouble();
}
/// divide (without loosing precision).
/// 两个数相除(防止精度丢失)
static double divideNum(num a, num b) {
return divideDec(a, b).toDouble();
}
/// 加 (精确相加,防止精度丢失).
/// add (without loosing precision).
static Decimal addDec(num a, num b) {
return addDecString(a.toString(), b.toString());
}
/// 减 (精确相减,防止精度丢失).
/// subtract (without loosing precision).
static Decimal subtractDec(num a, num b) {
return subtractDecString(a.toString(), b.toString());
}
/// 乘 (精确相乘,防止精度丢失).
/// multiply (without loosing precision).
static Decimal multiplyDec(num a, num b) {
return multiplyDecString(a.toString(), b.toString());
}
/// 除 (精确相除,防止精度丢失).
/// divide (without loosing precision).
static Decimal divideDec(num a, num b) {
return divideDecString(a.toString(), b.toString());
}
/// 余数
static Decimal remainder(num a, num b) {
return remainderDecString(a.toString(), b.toString());
}
/// Relational less than operator.
/// 关系小于运算符。判断a是否小于b
static bool lessThan(num a, num b) {
return lessThanDecString(a.toString(), b.toString());
}
/// Relational less than or equal operator.
/// 关系小于或等于运算符。判断a是否小于或者等于b
static bool thanOrEqual(num a, num b) {
return thanOrEqualDecString(a.toString(), b.toString());
}
/// Relational greater than operator.
/// 关系大于运算符。判断a是否大于b
static bool greaterThan(num a, num b) {
return greaterThanDecString(a.toString(), b.toString());
}
/// Relational greater than or equal operator.
static bool greaterOrEqual(num a, num b) {
return greaterOrEqualDecString(a.toString(), b.toString());
}
/// 两个数相加(防止精度丢失)
static Decimal addDecString(String a, String b) {
return Decimal.parse(a) + Decimal.parse(b);
}
/// 减
static Decimal subtractDecString(String a, String b) {
return Decimal.parse(a) - Decimal.parse(b);
}
/// 乘
static Decimal multiplyDecString(String a, String b) {
return Decimal.parse(a) * Decimal.parse(b);
}
/// 除
static Decimal divideDecString(String a, String b) {
return Decimal.parse(a) / Decimal.parse(b);
}
/// 余数
static Decimal remainderDecString(String a, String b) {
return Decimal.parse(a) % Decimal.parse(b);
}
/// Relational less than operator.
/// 判断a是否小于b
static bool lessThanDecString(String a, String b) {
return Decimal.parse(a) < Decimal.parse(b);
}
/// Relational less than or equal operator.
/// 判断a是否小于或者等于b
static bool thanOrEqualDecString(String a, String b) {
return Decimal.parse(a) <= Decimal.parse(b);
}
/// Relational greater than operator.
/// 判断a是否大于b
static bool greaterThanDecString(String a, String b) {
return Decimal.parse(a) > Decimal.parse(b);
}
/// Relational greater than or equal operator.
static bool greaterOrEqualDecString(String a, String b) {
return Decimal.parse(a) >= Decimal.parse(b);
}
/// Checks if num a LOWER than num b.
/// 检查num a是否小于num b。
static bool isLowerThan(num a, num b) => a < b;
/// Checks if num a GREATER than num b.
/// 检查num a是否大于num b。
static bool isGreaterThan(num a, num b) => a > b;
/// Checks if num a EQUAL than num b.
/// 检查num a是否等于num b。
static bool isEqual(num a, num b) => a == b;
}
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/num/rational.dart | Dart |
final _pattern = RegExp(r'^([+-]?\d*)(\.\d*)?([eE][+-]?\d+)?$');
final _r0 = Rational.fromInt(0);
final _r1 = Rational.fromInt(1);
final _r5 = Rational.fromInt(5);
final _r10 = Rational.fromInt(10);
final _i0 = BigInt.zero;
final _i1 = BigInt.one;
final _i2 = BigInt.two;
final _i5 = BigInt.from(5);
final _i10 = BigInt.from(10);
final _i31 = BigInt.from(31);
class Rational implements Comparable<Rational> {
factory Rational(BigInt numerator, [BigInt denominator]) {
denominator ??= _i1;
if (denominator == _i0) throw ArgumentError();
if (numerator == _i0) return Rational._normalized(_i0, _i1);
if (denominator < _i0) {
numerator = -numerator;
denominator = -denominator;
}
final aNumerator = numerator.abs();
final aDenominator = denominator.abs();
final gcd = aNumerator.gcd(aDenominator);
return (gcd == _i1)
? Rational._normalized(numerator, denominator)
: Rational._normalized(numerator ~/ gcd, denominator ~/ gcd);
}
factory Rational.fromInt(int numerator, [int denominator = 1]) =>
Rational(BigInt.from(numerator), BigInt.from(denominator));
factory Rational.parse(String decimalValue) {
final match = _pattern.firstMatch(decimalValue);
if (match == null) {
throw FormatException('$decimalValue is not a valid format');
}
final group1 = match.group(1);
final group2 = match.group(2);
final group3 = match.group(3);
var numerator = _i0;
var denominator = _i1;
if (group2 != null) {
for (var i = 1; i < group2.length; i++) {
denominator = denominator * _i10;
}
numerator = BigInt.parse('$group1${group2.substring(1)}');
} else {
numerator = BigInt.parse(group1);
}
if (group3 != null) {
var exponent = BigInt.parse(group3.substring(1));
while (exponent > _i0) {
numerator = numerator * _i10;
exponent -= _i1;
}
while (exponent < _i0) {
denominator = denominator * _i10;
exponent += _i1;
}
}
return Rational(numerator, denominator);
}
Rational._normalized(this.numerator, this.denominator)
: assert(numerator != null),
assert(denominator != null),
assert(denominator > _i0),
assert(numerator.abs().gcd(denominator) == _i1);
final BigInt numerator, denominator;
static final zero = Rational.fromInt(0);
static final one = Rational.fromInt(1);
bool get isInteger => denominator == _i1;
Rational get inverse => Rational(denominator, numerator);
@override
int get hashCode => (numerator + _i31 * denominator).hashCode;
@override
bool operator ==(Object other) =>
other is Rational &&
numerator == other.numerator &&
denominator == other.denominator;
@override
String toString() {
if (numerator == _i0) return '0';
if (isInteger) {
return '$numerator';
} else {
return '$numerator/$denominator';
}
}
String toDecimalString() {
if (isInteger) return toStringAsFixed(0);
final fractionDigits = hasFinitePrecision ? scale : 10;
var asString = toStringAsFixed(fractionDigits);
while (asString.contains('.') &&
(asString.endsWith('0') || asString.endsWith('.'))) {
asString = asString.substring(0, asString.length - 1);
}
return asString;
}
// implementation of Comparable
@override
int compareTo(Rational other) =>
(numerator * other.denominator).compareTo(other.numerator * denominator);
// implementation of num
Rational operator +(Rational other) => Rational(
numerator * other.denominator + other.numerator * denominator,
denominator * other.denominator);
Rational operator -(Rational other) => Rational(
numerator * other.denominator - other.numerator * denominator,
denominator * other.denominator);
Rational operator *(Rational other) =>
Rational(numerator * other.numerator, denominator * other.denominator);
Rational operator %(Rational other) {
final remainder = this.remainder(other);
if (remainder == _r0) return _r0;
return remainder + (isNegative ? other.abs() : _r0);
}
Rational operator /(Rational other) =>
Rational(numerator * other.denominator, denominator * other.numerator);
/// Truncating division operator.
///
/// The result of the truncating division [:a ~/ b:] is equivalent to
/// [:(a / b).truncate():].
Rational operator ~/(Rational other) => (this / other).truncate();
Rational operator -() => Rational._normalized(-numerator, denominator);
/// Return the remainder from dividing this [num] by [other].
Rational remainder(Rational other) => this - (this ~/ other) * other;
bool operator <(Rational other) => compareTo(other) < 0;
bool operator <=(Rational other) => compareTo(other) <= 0;
bool operator >(Rational other) => compareTo(other) > 0;
bool operator >=(Rational other) => compareTo(other) >= 0;
bool get isNaN => false;
bool get isNegative => numerator < _i0;
bool get isInfinite => false;
/// Returns the absolute value of this [num].
Rational abs() => isNegative ? (-this) : this;
/// The signum function value of this [num].
///
/// E.e. -1, 0 or 1 as the value of this [num] is negative, zero or positive.
int get signum {
final v = compareTo(_r0);
if (v < 0) return -1;
if (v > 0) return 1;
return 0;
}
/// Returns the integer value closest to this [num].
///
/// Rounds away from zero when there is no closest integer:
/// [:(3.5).round() == 4:] and [:(-3.5).round() == -4:].
Rational round() {
final abs = this.abs();
final absBy10 = abs * _r10;
var r = abs.truncate();
if (absBy10 % _r10 >= _r5) r += _r1;
return isNegative ? -r : r;
}
/// Returns the greatest integer value no greater than this [num].
Rational floor() =>
isInteger ? truncate() : isNegative ? (truncate() - _r1) : truncate();
/// Returns the least integer value that is no smaller than this [num].
Rational ceil() =>
isInteger ? truncate() : isNegative ? truncate() : (truncate() + _r1);
/// Returns the integer value obtained by discarding any fractional digits
/// from this [num].
Rational truncate() => Rational._normalized(numerator ~/ denominator, _i1);
/// Returns the integer value closest to `this`.
///
/// Rounds away from zero when there is no closest integer:
/// [:(3.5).round() == 4:] and [:(-3.5).round() == -4:].
///
/// The result is a double.
double roundToDouble() => round().toDouble();
/// Returns the greatest integer value no greater than `this`.
///
/// The result is a double.
double floorToDouble() => floor().toDouble();
/// Returns the least integer value no smaller than `this`.
///
/// The result is a double.
double ceilToDouble() => ceil().toDouble();
/// Returns the integer obtained by discarding any fractional digits from
/// `this`.
///
/// The result is a double.
double truncateToDouble() => truncate().toDouble();
/// Clamps the rational to be in the range [lowerLimit]-[upperLimit]. The
/// comparison is done using [compareTo] and therefore takes [:-0.0:] into
/// account.
Rational clamp(Rational lowerLimit, Rational upperLimit) =>
this < lowerLimit ? lowerLimit : this > upperLimit ? upperLimit : this;
/// Truncates this [num] to an integer and returns the result as an [int].
int toInt() => toBigInt().toInt();
/// Truncates this [num] to a big integer and returns the result as an
/// [BigInt].
BigInt toBigInt() => numerator ~/ denominator;
/// Return this [num] as a [double].
///
/// If the number is not representable as a [double], an approximation is
/// returned. For numerically large integers, the approximation may be
/// infinite.
double toDouble() => numerator / denominator;
/// Inspect if this [num] has a finite precision.
bool get hasFinitePrecision {
// the denominator should only be a product of powers of 2 and 5
var den = denominator;
while (den % _i5 == _i0) {
den = den ~/ _i5;
}
while (den % _i2 == _i0) {
den = den ~/ _i2;
}
return den == _i1;
}
/// The precision of this [num].
///
/// The sum of the number of digits before and after the decimal point.
///
/// **WARNING for dart2js** : It can give bad result for large number.
///
/// Throws [StateError] if the precision is infinite, i.e. when
/// [hasFinitePrecision] is `false`.
int get precision {
if (!hasFinitePrecision) {
throw StateError('This number has an infinite precision: $this');
}
var x = numerator;
while (x % denominator != _i0) {
x *= _i10;
}
x = x ~/ denominator;
return x.abs().toString().length;
}
/// The scale of this [num].
///
/// The number of digits after the decimal point.
///
/// **WARNING for dart2js** : It can give bad result for large number.
///
/// Throws [StateError] if the scale is infinite, i.e. when
/// [hasFinitePrecision] is `false`.
int get scale {
if (!hasFinitePrecision) {
throw StateError('This number has an infinite precision: $this');
}
var i = 0;
var x = numerator;
while (x % denominator != _i0) {
i++;
x *= _i10;
}
return i;
}
/// Converts a [num] to a string representation with [fractionDigits] digits
/// after the decimal point.
String toStringAsFixed(int fractionDigits) {
if (fractionDigits == 0) {
return round().toBigInt().toString();
} else {
var mul = _i1;
for (var i = 0; i < fractionDigits; i++) {
mul *= _i10;
}
final mulRat = Rational(mul);
final lessThanOne = abs() < _r1;
final tmp = (lessThanOne ? (abs() + _r1) : abs()) * mulRat;
final tmpRound = tmp.round();
final intPart =
(lessThanOne ? ((tmpRound ~/ mulRat) - _r1) : (tmpRound ~/ mulRat))
.toBigInt();
final decimalPart =
tmpRound.toBigInt().toString().substring(intPart.toString().length);
return '${isNegative ? '-' : ''}$intPart.$decimalPart';
}
}
/// Converts a [num] to a string in decimal exponential notation with
/// [fractionDigits] digits after the decimal point.
String toStringAsExponential([int fractionDigits]) =>
toDouble().toStringAsExponential(fractionDigits);
/// Converts a [num] to a string representation with [precision] significant
/// digits.
String toStringAsPrecision(int precision) {
assert(precision > 0);
if (this == _r0) {
return precision == 1 ? '0' : '0.'.padRight(1 + precision, '0');
}
var limit = _r1;
for (var i = 0; i < precision; i++) {
limit *= _r10;
}
var shift = _r1;
var pad = 0;
while (abs() * shift < limit) {
pad++;
shift *= _r10;
}
while (abs() * shift >= limit) {
pad--;
shift /= _r10;
}
final value = (this * shift).round() / shift;
return pad <= 0 ? value.toString() : value.toStringAsFixed(pad);
}
/// Returns `this` to the power of [exponent].
///
/// Returns [one] if the [exponent] equals `0`.
///
/// The [exponent] must otherwise be positive.
Rational pow(int exponent) =>
Rational(numerator.pow(exponent), denominator.pow(exponent));
}
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/object/object_utils.dart | Dart |
/// Object 工具类
class ObjectUtils {
/// 判断对象是否为null
static bool isNull(dynamic s) => s == null;
/// Checks if data is null or blank (empty or only contains whitespace).
/// 检查数据是否为空或空(空或只包含空格)
static bool isNullOrBlank(dynamic s) {
if (isNull(s)) return true;
switch (s.runtimeType) {
case String:
case List:
case Map:
case Set:
case Iterable:
return s.isEmpty;
break;
default:
return s.toString() == 'null' || s.toString().trim().isEmpty;
}
}
/// Returns true if the string is null or 0-length.
/// 判断字符串是否为空
static bool isEmptyString(String str) {
return str == null || str.isEmpty;
}
/// Returns true if the list is null or 0-length.
/// 判断集合是否为空
static bool isEmptyList(Iterable list) {
return list == null || list.isEmpty;
}
/// Returns true if there is no key/value pair in the map.
/// 判断字典是否为空
static bool isEmptyMap(Map map) {
return map == null || map.isEmpty;
}
/// Returns true String or List or Map is empty.
/// 判断object对象是否为空
static bool isEmpty(Object object) {
if (object == null) return true;
if (object is String && object.isEmpty) {
return true;
} else if (object is Iterable && object.isEmpty) {
return true;
} else if (object is Map && object.isEmpty) {
return true;
}
return false;
}
/// Returns true String or List or Map is not empty.
/// 判断object是否不为空
static bool isNotEmpty(Object object) {
return !isEmpty(object);
}
/// Returns true Two List Is Equal.
/// 比较两个集合是否相同
static bool compareListIsEqual(List listA, List listB) {
if (listA == listB) return true;
if (listA == null || listB == null) return false;
int length = listA.length;
if (length != listB.length) return false;
for (int i = 0; i < length; i++) {
if (!listA.contains(listB[i])) {
return false;
}
}
return true;
}
/// get length.
/// 获取object的长度
static int getLength(Object value) {
if (value == null) return 0;
if (value is String) {
return value.length;
} else if (value is Iterable) {
return value.length;
} else if (value is Map) {
return value.length;
} else {
return 0;
}
}
}
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/parsing/elements.dart | Dart | import 'dart:convert';
import 'package:yc_flutter_utils/parsing/markup_utils.dart';
import 'package:yc_flutter_utils/parsing/node_type.dart';
/// 这是一个HTML/XML元素,由下面这些组成
/// [RootNode],[ElementNode],[TextNode],[CommentNode]
abstract class Node {
String type;
String tag;
String text;
List<Attribute> attributes;
List<Node> children;
Node(this.type, {this.tag, this.text, this.attributes, this.children});
Map<String, dynamic> toMap() {
Map<String, dynamic> map = {"type": type};
if (tag != null) map["tag"] = tag;
if (text != null) map["text"] = text;
if (attributes != null) {
map["attributes"] =
attributes.map((attribute) => attribute.toMap()).toList();
}
if (children != null) {
map["children"] = children.map((child) => child.toMap()).toList();
}
return map;
}
String toMarKup() {
return MarkupUtils.mapToMarkup(toMap());
}
String toJson() {
return toString();
}
String toString() {
return jsonEncode(toMap());
}
}
/// 它是JSON的起点,它包含实际的HTML/XML元素的子元素。
/// 开始标记。它拥有孩子。
class RootNode extends Node {
String type = NodeType.ROOT;
List<Node> children;
RootNode(this.children) : super(NodeType.ROOT, children: children);
}
/// 它是包含属性和子元素的HTML/XML标记。
/// 应该指定标签(例如:div)。支持属性和子元素。
class ElementNode extends Node {
String type = NodeType.ELEMENT;
String tag;
List<Attribute> attributes;
List<Node> children;
ElementNode({this.tag, this.attributes, this.children})
: super(NodeType.ELEMENT,
tag: tag, attributes: attributes, children: children);
}
/// 它是HTML/XML元素中的文本内容。
/// 比如. <div>Hello world!</div>
/// 那么: `Hello world!` is the TextNode
/// 它是出现在HTML/Markup标签内的文本。
class TextNode extends Node {
String type = NodeType.TEXT;
String text;
TextNode(this.text) : super(NodeType.TEXT, text: text);
}
/// 它是节点之间的注释
/// 它是一个注释,可以放在元素之间,
class CommentNode extends Node {
String type = NodeType.COMMENT;
String text;
CommentNode(this.text) : super(NodeType.COMMENT, text: text);
}
/// 有HTML/XML元素的属性。所以只有[ElementNode]支持属性。
class Attribute {
String name;
String value;
String valueOriginal;
Attribute(this.name, this.value, [this.valueOriginal]) {
if (valueOriginal == null) {
valueOriginal = '"$value"';
}
}
Map<String, dynamic> toMap() {
return {"name": name, "value": value, "valueOriginal": valueOriginal};
}
String toJson() {
return toString();
}
@override
String toString() {
return jsonEncode(toMap());
}
}
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/parsing/html_parser.dart | Dart |
import 'Elements.dart';
var empty = makeMap(
"area,base,basefont,br,col,frame,hr,img,input,link,meta,param,embed,command,keygen,source,track,wbr, ?xml");
var special = makeMap("script,style");
/// 解析HTML/XML元素并返回' start ', ' end ', ' comment ', ' chars '。
/// 基于这些回调函数构造JSON。
class HtmlParser {
var index, chars;
List<String> stack = [];
String match, last;
Map<String, Function> handler;
String stackLast() {
if (stack.isEmpty) return "";
return stack[stack.length - 1];
}
HtmlParser(String html, Map<String, Function> handler) {
last = html;
this.handler = handler;
;
while (html.isNotEmpty) {
chars = true;
if (html.indexOf("<!--") == 0) {
index = html.indexOf("-->");
if (index >= 0) {
handler["comment"](html.substring(4, index));
html = html.substring(index + 3);
chars = false;
}
} else if (html.indexOf("</") == 0) {
match = RegExp(r"^<([\s\S]*?)>").stringMatch(html);
var matchLength = match.length;
if (match != null && matchLength > 0) {
html = html.substring(matchLength);
match = match.substring(2, matchLength - 1);
parseEndTag(match);
chars = false;
}
} else if (html.indexOf("<") == 0) {
if ((match = RegExp(r"^<([\s\S]*?)>").stringMatch(html)) != null &&
match.isNotEmpty) {
var matchLength = match.length;
html = html.substring(matchLength);
if (match.endsWith(r"/>")) {
match = match.substring(1, matchLength - 2);
parseStartTag(match, match.split(" ")[0], true);
} else {
match = match.substring(1, matchLength - 1);
parseStartTag(match, match.split(" ")[0], false);
}
}
chars = false;
}
if (chars) {
index = html.indexOf("<");
var text = index < 0 ? html : html.substring(0, index);
html = index < 0 ? "" : html.substring(index);
if (text.trim().isNotEmpty) handler["chars"](text);
}
if (html == last) throw "Parse Error: " + html;
last = html;
}
parseEndTag();
}
parseStartTag(String tag, String tagName, bool unary) {
unary = empty[tagName] == true || unary;
if (!unary) stack.add(tagName);
var rest = tag.replaceFirst(tagName, '').trim();
var attrRegExp = RegExp(
r"""([a-zA-Z_:@#][-a-zA-Z0-9_:.]*)(?:\s*=(\s*(?:(?:"((?:\\.|[^"])*)")|(?:'((?:\\.|[^'])*)')|([^>\s]+))))?""");
List<Attribute> attrs = attrRegExp.allMatches(rest).map((match) {
String value = match.group(2) != null
? match.group(2)
: match.group(3) != null
? match.group(3)
: match.group(4) != null ? match.group(4) : "";
return Attribute(match.group(1),
value.isEmpty ? "" : value.substring(1, value.length - 1), value);
}).toList();
handler["start"](tagName, attrs, unary);
}
parseEndTag([String tagName = ""]) {
if (tagName.trim().isNotEmpty) handler["end"](tagName);
}
}
Map<String, bool> makeMap(str) {
var obj = Map<String, bool>(), items = str.split(",");
for (var i = 0; i < items.length; i++) {
obj[items[i]] = true;
}
return obj;
}
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/parsing/markup_utils.dart | Dart | import 'dart:convert';
import 'package:yc_flutter_utils/parsing/html_parser.dart';
import 'package:yc_flutter_utils/parsing/node_type.dart';
import 'Elements.dart';
class MarkupUtils {
///Converts [Map] to [Node]
static Node mapToNode(Map<String, dynamic> json) {
dynamic node;
switch (json["type"]) {
case NodeType.ROOT:
node = RootNode(null);
break;
case NodeType.ELEMENT:
node = ElementNode(tag: json["tag"]);
break;
case NodeType.TEXT:
node = TextNode(json["text"]);
break;
case NodeType.COMMENT:
node = CommentNode(json["text"]);
break;
}
if (json["children"] != null) {
node.children =
(json["children"] as List<dynamic>).map((c) => mapToNode(c)).toList();
}
if (json["attributes"] != null) {
node.attributes = (json["attributes"] as List<dynamic>)
.map((attr) =>
Attribute(attr["name"], attr["value"], attr["valueOriginal"]))
.toList();
}
return node;
}
///Converts json to [Node]
static Node jsonToNode(String jsonString) {
return mapToNode(jsonDecode(jsonString));
}
/// Removes DOCTYPE
/// 删除文档类型
static _removeDOCTYPE(String html) {
String xmlType;
if ((xmlType = RegExp(r"<\?xml.*\?>").stringMatch(html)) != null) {
html = html.replaceFirst(xmlType, '');
}
String hxmlType1;
if ((hxmlType1 = RegExp(r"<!doctype.*\>").stringMatch(html)) != null) {
html = html.replaceFirst(hxmlType1, '');
}
String hxmlType2;
if ((hxmlType2 = RegExp(r"<!DOCTYPE.*\>").stringMatch(html)) != null) {
html = html.replaceFirst(hxmlType2, '');
}
return html;
}
/// 将HTML/XML字符串转换为[Node]
static Node markup2json(String markupString) {
markupString = _removeDOCTYPE(markupString);
List<Node> bufArray = [];
RootNode results = RootNode([]);
HtmlParser(markupString, {
"start": (String tag, List<Attribute> attrs, bool unary) {
ElementNode elementNode = ElementNode(tag: tag.trim());
if (attrs.isNotEmpty) {
elementNode.attributes = attrs;
}
if (unary) {
var parent =
(bufArray.isNotEmpty ? bufArray[0] : results) as ElementNode;
if (parent.children == null) {
parent.children = [];
}
parent.children.add(elementNode);
} else {
bufArray.insert(0, elementNode);
}
},
"end": (String tag) {
if (tag.trim().isEmpty) return;
var node = bufArray.removeAt(0) as ElementNode;
if (node.tag != tag) print('invalid state: mismatch end tag: $node');
if (bufArray.isEmpty) {
results.children.add(node);
} else {
var parent = bufArray[0] as ElementNode;
if (parent.children == null) {
parent.children = [];
}
parent.children.add(node);
}
},
"chars": (String text) {
if (text.trim().isEmpty) {
return;
}
TextNode textNode = TextNode(text);
if (bufArray.isEmpty) {
results.children.add(textNode);
} else {
var parent = bufArray[0] as ElementNode;
if (parent.children == null) {
parent.children = [];
}
parent.children.add(textNode);
}
},
"comment": (String text) {
CommentNode commentNode = CommentNode(text);
var parent = bufArray[0] as ElementNode;
if (parent.children == null) {
parent.children = [];
}
parent.children.add(commentNode);
}
});
return results;
}
/// Converts jsonString to markupString
/// 将json字符串转换为标记字符串
static String jsonToMarkup(String jsonString) =>
_parse(jsonDecode(jsonString));
///Converts [Map] to markupString
static String mapToMarkup(Map<String, dynamic> jsonMap) => _parse(jsonMap);
///Converts [Map] to markupString
static String _parse(Map<String, dynamic> json) {
var child = '';
if (json["children"] != null) {
child = (json["children"] as List<dynamic>).map((c) {
return _parse(c);
}).join('');
}
var attr = '';
if (json["attributes"] != null) {
attr = (json["attributes"] as List<dynamic>).map((attrObj) {
if (attrObj['valueOriginal'].toString().isEmpty) return attrObj['name'];
return '${attrObj['name']}=${attrObj['valueOriginal']}';
}).join(' ');
if (attr.isNotEmpty) attr = ' ' + attr;
}
if (json["type"] == NodeType.ELEMENT) {
var tag = json["tag"].toString();
if (json["children"] == null) {
return '<' + tag + attr + '/>';
}
var open = '<' + tag + attr + '>';
var close = '</' + tag + '>';
return open + child + close;
}
if (json["type"] == NodeType.TEXT) {
return json["text"];
}
if (json["type"] == NodeType.COMMENT) {
return '<!--' + json["text"] + '-->';
}
if (json["type"] == NodeType.ROOT) {
return child;
}
return child;
}
}
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/parsing/node_type.dart | Dart |
/// 这些是受支持的节点类型。
class NodeType {
static const String ROOT = "root";
static const String ELEMENT = "element";
static const String TEXT = "text";
static const String COMMENT = "comment";
} | yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/regex/regex_constants.dart | Dart |
/// 正则表达式的常量,参考AndroidUtils:https://github.com/Blankj/AndroidUtilCode
class RegexConstants{
///Regex of simple mobile.
///简单移动电话的正则表达式
static const String REGEX_MOBILE_SIMPLE = "^[1]\\d{10}\$";
/// Regex of exact mobile.
/// <p>china mobile: 134(0-8), 135, 136, 137, 138, 139, 147, 150, 151, 152, 157, 158, 159, 165, 172, 178, 182, 183, 184, 187, 188, 195, 197, 198</p>
/// <p>china unicom: 130, 131, 132, 145, 155, 156, 166, 167, 175, 176, 185, 186, 196</p>
/// <p>china telecom: 133, 149, 153, 162, 173, 177, 180, 181, 189, 190, 191, 199</p>
/// <p>china broadcasting: 192</p>
/// <p>global star: 1349</p>
/// <p>virtual operator: 170, 171</p>
static const String REGEX_MOBILE_EXACT =
"^((13[0-9])|(14[579])|(15[0-35-9])|(16[2567])|(17[0-35-8])|(18[0-9])|(19[0-35-9]))\\d{8}\$";
/// Regex of telephone number.
static const String REGEX_TEL =
"^0\\d{2,3}[- ]?\\d{7,8}\$";
/// Regex of id card number which length is 15.
static const String regexIdCard15 =
'^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}\$';
/// Regex of id card number which length is 15.
static const String REGEX_ID_CARD15 =
"^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}\$";
/// Regex of id card number which length is 18.
static const String REGEX_ID_CARD18 =
"^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([0-9Xx])\$";
///Regex of email.
static const String REGEX_EMAIL =
"^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*\$";
///Regex of url.
static const String REGEX_URL =
"[a-zA-z]+://[^\\s]*";
///Regex of Chinese character.
static const String REGEX_ZH =
"^[\\u4e00-\\u9fa5]+\$";
/// Regex of username.
/// <p>scope for "a-z", "A-Z", "0-9", "_", "Chinese character"</p>
/// <p>can't end with "_"</p>
/// <p>length is between 6 to 20</p>
static const String REGEX_USERNAME =
"^[\\w\\u4e00-\\u9fa5]{6,20}(?<!_)\$";
/// must contain letters and numbers, 6 ~ 18.
/// 必须包含字母和数字, 6~18.
static const String REGEX_USERNAME1 =
'^(?![0-9]+\$)(?![a-zA-Z]+\$)[0-9A-Za-z]{6,18}\$';
/// must contain letters and numbers, can contain special characters 6 ~ 18.
/// 必须包含字母和数字,可包含特殊字符 6~18.
static const String REGEX_USERNAME2 =
'^(?![0-9]+\$)(?![a-zA-Z]+\$)[0-9A-Za-z\\W]{6,18}\$';
/// must contain letters and numbers and special characters, 6 ~ 18.
/// 必须包含字母和数字和殊字符, 6~18.
static const String REGEX_USERNAME3 =
'^(?![0-9]+\$)(?![a-zA-Z]+\$)(?![0-9a-zA-Z]+\$)(?![0-9\\W]+\$)(?![a-zA-Z\\W]+\$)[0-9A-Za-z\\W]{6,18}\$';
/// Regex of date which pattern is "yyyy-MM-dd".
static const String REGEX_DATE =
"^(?:(?!0000)[0-9]{4}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-8])|(?:0[13-9]|1[0-2])-(?:29|30)|(?:0[13578]|1[02])-31)|(?:[0-9]{2}(?:0[48]|[2468][048]|[13579][26])|(?:0[48]|[2468][048]|[13579][26])00)-02-29)\$";
/// Regex of ip address.
static const String REGEX_IP =
"((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)";
///////////////////////////////////////////////////////////////////////////
// The following come from http://tool.oschina.net/regex
///////////////////////////////////////////////////////////////////////////
/// Regex of double-byte characters.
static const String REGEX_DOUBLE_BYTE_CHAR =
"[^\\x00-\\xff]";
/// Regex of blank line.
static const String REGEX_BLANK_LINE =
"\\n\\s*\\r";
/// Regex of QQ number.
static const String REGEX_QQ_NUM =
"[1-9][0-9]{4,}";
/// Regex of postal code in China.
static const String REGEX_CHINA_POSTAL_CODE =
"[1-9]\\d{5}(?!\\d)";
/// Regex of integer.
static const String REGEX_INTEGER =
"^(-?[1-9]\\d*)|0\$";
/// Regex of positive integer.
static const String REGEX_POSITIVE_INTEGER =
"^[1-9]\\d*\$";
/// Regex of negative integer.
static const String REGEX_NEGATIVE_INTEGER =
"^-[1-9]\\d*\$";
/// Regex of non-negative integer.
static const String REGEX_NOT_NEGATIVE_INTEGER =
"^[1-9]\\d*|0\$";
/// Regex of non-positive integer.
static const String REGEX_NOT_POSITIVE_INTEGER =
"^-[1-9]\\d*|0\$";
/// Regex of positive float.
static const String REGEX_FLOAT =
"^-?([1-9]\\d*\\.\\d*|0\\.\\d*[1-9]\\d*|0?\\.0+|0)\$";
/// Regex of positive float.
static const String REGEX_POSITIVE_FLOAT =
"^[1-9]\\d*\\.\\d*|0\\.\\d*[1-9]\\d*\$";
/// Regex of negative float.
static const String REGEX_NEGATIVE_FLOAT =
"^-[1-9]\\d*\\.\\d*|-0\\.\\d*[1-9]\\d*\$";
/// Regex of positive float.
static const String REGEX_NOT_NEGATIVE_FLOAT =
"^[1-9]\\d*\\.\\d*|0\\.\\d*[1-9]\\d*|0?\\.0+|0\$";
///Regex of negative float.
///
static const String REGEX_NOT_POSITIVE_FLOAT =
"^(-([1-9]\\d*\\.\\d*|0\\.\\d*[1-9]\\d*))|0?\\.0+|0\$";
/// Email regex
/// email正则表达式
static Pattern email =
r'^[a-z0-9]+([-+._][a-z0-9]+){0,2}@.*?(\.(a(?:[cdefgilmnoqrstuwxz]|ero|(?:rp|si)a)|b(?:[abdefghijmnorstvwyz]iz)|c(?:[acdfghiklmnoruvxyz]|at|o(?:m|op))|d[ejkmoz]|e(?:[ceghrstu]|du)|f[ijkmor]|g(?:[abdefghilmnpqrstuwy]|ov)|h[kmnrtu]|i(?:[delmnoqrst]|n(?:fo|t))|j(?:[emop]|obs)|k[eghimnprwyz]|l[abcikrstuvy]|m(?:[acdeghklmnopqrstuvwxyz]|il|obi|useum)|n(?:[acefgilopruz]|ame|et)|o(?:m|rg)|p(?:[aefghklmnrstwy]|ro)|qa|r[eosuw]|s[abcdeghijklmnortuvyz]|t(?:[cdfghjklmnoprtvwz]|(?:rav)?el)|u[agkmsyz]|v[aceginu]|w[fs]|y[etu]|z[amw])\b){1,2}$';
/// URL regex
/// Eg:
/// - https://medium.com/@diegoveloper/flutter-widget-size-and-position-b0a9ffed9407
/// - https://www.youtube.com/watch?v=COYFmbVEH0k
/// - https://stackoverflow.com/questions/53913192/flutter-change-the-width-of-an-alertdialog/57688555
static Pattern url =
r"^((((H|h)(T|t)|(F|f))(T|t)(P|p)((S|s)?))\://)?(www.|[a-zA-Z0-9].)[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,6}(\:[0-9]{1,5})*(/($|[a-zA-Z0-9\.\,\;\?\'\\\+&%\$#\=~_\-@]+))*$";
/// Hexadecimal regex
static Pattern hexadecimal = r'^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$';
/// Image vector regex
/// 图像向量正则表达式
static Pattern vector = r'.(svg)$';
/// Image regex
/// 图像正则表达式
static Pattern image = r'.(jpeg|jpg|gif|png|bmp)$';
/// Audio regex
/// 音频正则表达式
static Pattern audio = r'.(mp3|wav|wma|amr|ogg)$';
/// Video regex
/// 视频正则表达式
static Pattern video = r'.(mp4|avi|wmv|rmvb|mpg|mpeg|3gp)$';
/// Txt regex
/// 文本正则表达式
static Pattern txt = r'.txt$';
/// Document regex
/// word正则表达式
static Pattern doc = r'.(doc|docx)$';
/// Excel regex
/// Excel正则表达式
static Pattern excel = r'.(xls|xlsx)$';
/// PPT regex
/// ppt正则表达式
static Pattern ppt = r'.(ppt|pptx)$';
/// Document regex
/// apk正则表达式
static Pattern apk = r'.apk$';
/// PDF regex
/// pdf正则表达式
static Pattern pdf = r'.pdf$';
/// HTML regex
/// html正则表达式
static Pattern html = r'.html$';
/// DateTime regex (UTC)
/// 时间正则表达式
/// Unformatted date time (UTC and Iso8601)
/// Example: 2020-04-27 08:14:39.977, 2020-04-27T08:14:39.977, 2020-04-27 01:14:39.977Z
static Pattern basicDateTime =
r'^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}.\d{3}Z?$';
/// MD5 regex
/// md5正则表达式
static Pattern md5 = r'^[a-f0-9]{32}$';
/// SHA1 regex
/// sha1正则表达式
static Pattern sha1 =
r'(([A-Fa-f0-9]{2}\:){19}[A-Fa-f0-9]{2}|[A-Fa-f0-9]{40})';
/// SHA256 regex
/// sha256正则表达式
static Pattern sha256 =
r'([A-Fa-f0-9]{2}\:){31}[A-Fa-f0-9]{2}|[A-Fa-f0-9]{64}';
/// IPv4 regex
/// IPv4正则表达式
static Pattern ipv4 = r'^(?:(?:^|\.)(?:2(?:5[0-5]|[0-4]\d)|1?\d?\d)){4}$';
/// IPv6 regex
/// IPv6正则表达式
static Pattern ipv6 =
r'^((([0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}:[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){5}:([0-9A-Fa-f]{1,4}:)?[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){4}:([0-9A-Fa-f]{1,4}:){0,2}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){3}:([0-9A-Fa-f]{1,4}:){0,3}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){2}:([0-9A-Fa-f]{1,4}:){0,4}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b))|(([0-9A-Fa-f]{1,4}:){0,5}:((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b))|(::([0-9A-Fa-f]{1,4}:){0,5}((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b))|([0-9A-Fa-f]{1,4}::([0-9A-Fa-f]{1,4}:){0,5}[0-9A-Fa-f]{1,4})|(::([0-9A-Fa-f]{1,4}:){0,6}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){1,7}:))$';
/// Numeric Only regex (No Whitespace & Symbols)
/// 只有数字的正则表达式(没有空格和符号)
static Pattern numericOnly = r'^\d+$';
/// Alphabet Only regex (No Whitespace & Symbols)
/// 仅限字母正则表达式(无空格和符号)
static Pattern alphabetOnly = r'^[a-zA-Z]+$';
/// Password (Easy) Regex
/// Allowing all character except 'whitespace'
/// Minimum character: 8
static Pattern passwordEasy = r'^\S{8,}$';
/// Password (Easy) Regex
/// Allowing all character
/// Minimum character: 8
static Pattern passwordEasyAllowedWhitespace = r'^[\S ]{8,}$';
/// Password (Normal) Regex
/// Allowing all character except 'whitespace'
/// Must contains at least: 1 letter & 1 number
/// Minimum character: 8
static Pattern passwordNormal1 = r'^(?=.*[A-Za-z])(?=.*\d)\S{8,}$';
/// Password (Normal) Regex
/// Allowing all character
/// Must contains at least: 1 letter & 1 number
/// Minimum character: 8
static Pattern passwordNormal1AllowedWhitespace =
r'^(?=.*[A-Za-z])(?=.*\d)[\S ]{8,}$';
/// Password (Normal) Regex
/// Allowing LETTER and NUMBER only
/// Must contains at least: 1 letter & 1 number
/// Minimum character: 8
static Pattern passwordNormal2 = r'^(?=.*[A-Za-z])(?=.*\d)[a-zA-Z0-9]{8,}$';
/// Password (Normal) Regex
/// Allowing LETTER and NUMBER only
/// Must contains: 1 letter & 1 number
/// Minimum character: 8
static Pattern passwordNormal2AllowedWhitespace =
r'^(?=.*[A-Za-z])(?=.*\d)[a-zA-Z0-9 ]{8,}$';
/// Password (Normal) Regex
/// Allowing all character except 'whitespace'
/// Must contains at least: 1 uppercase letter, 1 lowecase letter & 1 number
/// Minimum character: 8
static Pattern passwordNormal3 = r'^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)\S{8,}$';
/// Password (Normal) Regex
/// Allowing all character
/// Must contains at least: 1 uppercase letter, 1 lowecase letter & 1 number
/// Minimum character: 8
static Pattern passwordNormal3AllowedWhitespace =
r'^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[\S ]{8,}$';
/// Password (Hard) Regex
/// Allowing all character except 'whitespace'
/// Must contains at least: 1 uppercase letter, 1 lowecase letter, 1 number, & 1 special character (symbol)
/// Minimum character: 8
static Pattern passwordHard =
r'^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[\W_])\S{8,}$';
/// Password (Hard) Regex
/// Allowing all character
/// Must contains at least: 1 uppercase letter, 1 lowecase letter, 1 number, & 1 special character (symbol)
/// Minimum character: 8
static Pattern passwordHardAllowedWhitespace =
r'^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[\W_])[\S ]{8,}$';
} | yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/regex/regex_utils.dart | Dart |
import 'package:yc_flutter_utils/regex/regex_constants.dart';
/// 常见正则表达式工具类
class RegexUtils {
static final Map<String, String> cityMap = Map();
/// Return whether input matches regex of simple mobile.
/// 判断输入字符串是否符合手机号
static bool isMobileSimple(String input) {
return matches(RegexConstants.REGEX_MOBILE_SIMPLE, input);
}
/// Return whether input matches regex of exact mobile.
/// 精确验证是否是手机号
static bool isMobileExact(String input) {
return matches(RegexConstants.REGEX_MOBILE_EXACT, input);
}
/// Return whether input matches regex of telephone number.
/// 判断返回输入是否匹配电话号码的正则表达式
static bool isTel(String input) {
return matches(RegexConstants.REGEX_TEL, input);
}
/// Return whether input matches regex of id card number.
/// 返回输入是否匹配身份证号码的正则表达式。
static bool isIDCard(String input) {
if (input.length == 15) {
return isIDCard15(input);
}
if (input.length == 18) {
return isIDCard18Exact(input);
}
return false;
}
/// Return whether input matches regex of id card number which length is 15.
/// 返回输入是否匹配长度为15的身份证号码的正则表达式。
static bool isIDCard15(String input) {
return matches(RegexConstants.REGEX_ID_CARD15, input);
}
/// Return whether input matches regex of id card number which length is 18.
/// 返回输入是否匹配长度为18的身份证号码的正则表达式。
static bool isIDCard18(String input) {
return matches(RegexConstants.REGEX_ID_CARD18, input);
}
/// Return whether input matches regex of exact id card number which length is 18.
/// 返回输入是否匹配长度为18的id卡号的正则表达式。
static bool isIDCard18Exact(String input) {
if (isIDCard18(input)) {
List<int> factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
List<String> suffix = [
'1',
'0',
'X',
'9',
'8',
'7',
'6',
'5',
'4',
'3',
'2'
];
if (cityMap.isEmpty) {
List<String> list = ID_CARD_PROVINCE_DICT;
List<MapEntry<String, String>> mapEntryList = [];
for (int i = 0, length = list.length; i < length; i++) {
List<String> tokens = list[i].trim().split('=');
MapEntry<String, String> mapEntry = MapEntry(tokens[0], tokens[1]);
mapEntryList.add(mapEntry);
}
cityMap.addEntries(mapEntryList);
}
if (cityMap[input.substring(0, 2)] != null) {
int weightSum = 0;
for (int i = 0; i < 17; ++i) {
weightSum += (input.codeUnitAt(i) - '0'.codeUnitAt(0)) * factor[i];
}
int idCardMod = weightSum % 11;
String idCardLast = String.fromCharCode(input.codeUnitAt(17));
return idCardLast == suffix[idCardMod];
}
}
return false;
}
/// Return whether input matches regex of email.
/// 返回输入是否匹配电子邮件的正则表达式。
static bool isEmail(String input) {
return matches(RegexConstants.REGEX_EMAIL, input);
}
/// Return whether input matches regex of url.
/// 返回输入是否匹配url的正则表达式。
static bool isURL(String input) {
return matches(RegexConstants.REGEX_URL, input);
}
/// Return whether input matches regex of Chinese character.
/// 返回输入是否匹配汉字的正则表达式。
static bool isZh(String input) {
return '〇' == input || matches(RegexConstants.REGEX_ZH, input);
}
/// Return whether input matches regex of date which pattern is 'yyyy-MM-dd'.
/// 返回输入是否匹配样式为'yyyy-MM-dd'的日期的正则表达式。
static bool isDate(String input) {
return matches(RegexConstants.REGEX_DATE, input);
}
/// Return whether input matches regex of ip address.
/// 返回输入是否匹配ip地址的正则表达式。
static bool isIP(String input) {
return matches(RegexConstants.REGEX_IP, input);
}
/// Return whether input matches regex of username.
/// 返回输入是否匹配用户名的正则表达式。
static bool isUserName(String input, {String regex = RegexConstants.REGEX_USERNAME}) {
return matches(regex, input);
}
/// Return whether input matches regex of QQ.
/// 返回是否匹配QQ的正则表达式。
static bool isQQ(String input) {
return matches(RegexConstants.REGEX_QQ_NUM, input);
}
/// Return whether input matches the regex.
/// 返回输入是否匹配正则表达式。
static bool matches(String regex, String input) {
if (input.isEmpty) {
return false;
}
return RegExp(regex).hasMatch(input);
}
/// 判断内容是否符合正则
static bool hasMatch(String s, Pattern p){
return (s == null) ? false : RegExp(p).hasMatch(s);
}
}
/// id card province dict.
List<String> ID_CARD_PROVINCE_DICT = [
'11=北京',
'12=天津',
'13=河北',
'14=山西',
'15=内蒙古',
'21=辽宁',
'22=吉林',
'23=黑龙江',
'31=上海',
'32=江苏',
'33=浙江',
'34=安徽',
'35=福建',
'36=江西',
'37=山东',
'41=河南',
'42=湖北',
'43=湖南',
'44=广东',
'45=广西',
'46=海南',
'50=重庆',
'51=四川',
'52=贵州',
'53=云南',
'54=西藏',
'61=陕西',
'62=甘肃',
'63=青海',
'64=宁夏',
'65=新疆',
'71=台湾老',
'81=香港',
'82=澳门',
'83=台湾新',
'91=国外',
];
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/router/animation_page_route.dart | Dart | import 'dart:ui';
import 'package:flutter/animation.dart';
import 'package:flutter/cupertino.dart';
import 'package:yc_flutter_utils/router/animation_type.dart';
final Tween<double> _tweenFade = Tween<double>(begin: 0, end: 1.0);
final Tween<Offset> _primaryTweenSlideFromBottomToTop =
Tween<Offset>(begin: const Offset(0.0, 1.0), end: Offset.zero);
final Tween<Offset> _secondaryTweenSlideFromBottomToTop =
Tween<Offset>(begin: Offset.zero, end: const Offset(0.0, -1.0));
final Tween<Offset> _primaryTweenSlideFromTopToBottom =
Tween<Offset>(begin: const Offset(0.0, -1.0), end: Offset.zero);
final Tween<Offset> _secondaryTweenSlideFromTopToBottom =
Tween<Offset>(begin: Offset.zero, end: const Offset(0.0, 1.0));
final Tween<Offset> _primaryTweenSlideFromRightToLeft =
Tween<Offset>(begin: const Offset(1.0, 0.0), end: Offset.zero);
final Tween<Offset> _secondaryTweenSlideFromRightToLeft =
Tween<Offset>(begin: Offset.zero, end: const Offset(-1.0, 0.0));
final Tween<Offset> _primaryTweenSlideFromLeftToRight =
Tween<Offset>(begin: const Offset(-1.0, 0.0), end: Offset.zero);
final Tween<Offset> _secondaryTweenSlideFromLeftToRight =
Tween<Offset>(begin: Offset.zero, end: const Offset(1.0, 0.0));
class AnimationPageRoute<T> extends PageRoute<T> {
AnimationPageRoute({
/// 必要参数要用@required 标注
@required this.builder,
this.isExitPageAffectedOrNot = true,
//从右到左的滑动
this.animationType = AnimationType.SlideRL,
RouteSettings settings,
this.maintainState = true,
bool fullscreenDialog = false,
}) : assert(builder != null),
/// 使用assert断言函数,
assert(isExitPageAffectedOrNot != null),
assert(animationType != null),
assert(maintainState != null),
assert(fullscreenDialog != null),
assert(opaque),
super(settings: settings, fullscreenDialog: fullscreenDialog);
final WidgetBuilder builder;
/// 该参数只针对当[AnimationType]为[SlideLR]或[SlideRL]新页面及当前页面动画均有效
final bool isExitPageAffectedOrNot;
/// 动画类型
final AnimationType animationType;
@override
final bool maintainState;
@override
Duration get transitionDuration => const Duration(milliseconds: 300);
@override
Color get barrierColor => null;
@override
String get barrierLabel => null;
@override
bool canTransitionTo(TransitionRoute<dynamic> nextRoute) =>
nextRoute is AnimationPageRoute && !nextRoute.fullscreenDialog;
@override
Widget buildPage(BuildContext context, Animation<double> animation,
Animation<double> secondaryAnimation) {
final Widget result = builder(context);
assert(() {
if (result == null) {
throw FlutterError.fromParts(<DiagnosticsNode>[
ErrorSummary(
'The builder for route "${settings.name}" returned null.'),
ErrorDescription('Route builders must never return null.')
]);
}
return true;
}());
return Semantics(
scopesRoute: true, explicitChildNodes: true, child: result);
}
@override
Widget buildTransitions(BuildContext context, Animation<double> animation,
Animation<double> secondaryAnimation, Widget child) {
if (animationType == AnimationType.Fade)
FadeTransition(
opacity: CurvedAnimation(
parent: animation,
curve: Curves.linearToEaseOut,
reverseCurve: Curves.easeInToLinear,
).drive(_tweenFade),
child: child);
final Curve curve = Curves.linear, reverseCurve = Curves.linear;
final TextDirection textDirection = Directionality.of(context);
Tween<Offset> primaryTween = _primaryTweenSlideFromRightToLeft,
secondTween = _secondaryTweenSlideFromRightToLeft;
if (animationType == AnimationType.SlideBT) {
primaryTween = _primaryTweenSlideFromBottomToTop;
} else if (animationType == AnimationType.SlideTB) {
primaryTween = _primaryTweenSlideFromTopToBottom;
} else if (animationType == AnimationType.SlideLR) {
primaryTween = _primaryTweenSlideFromLeftToRight;
secondTween = _secondaryTweenSlideFromLeftToRight;
}
Widget enterAnimWidget = SlideTransition(
position: CurvedAnimation(
parent: animation,
curve: curve,
reverseCurve: reverseCurve,
).drive(primaryTween),
textDirection: textDirection,
child: child);
if (isExitPageAffectedOrNot != true ||
([AnimationType.SlideTB, AnimationType.SlideBT]
.contains(animationType))) return enterAnimWidget;
return SlideTransition(
position: CurvedAnimation(
parent: secondaryAnimation,
curve: curve,
reverseCurve: reverseCurve,
).drive(secondTween),
textDirection: textDirection,
child: enterAnimWidget);
}
@override
String get debugLabel => '${super.debugLabel}(${settings.name})';
}
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/router/animation_type.dart | Dart |
/// 路由跳转动画类型枚举,`SlideRL`,`SlideLR`,`SlideTB`, `SlideBT`, `Fade`
enum AnimationType {
/// 从右到左的滑动
SlideRL,
/// 从左到右的滑动
SlideLR,
/// 从上到下的滑动
SlideTB,
/// 从下到上的滑动
SlideBT,
/// 透明过渡
Fade,
}
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/router/fade_route.dart | Dart |
import 'package:flutter/material.dart';
///定义一个路由类FadeRoute
///无论是MaterialPageRoute、CupertinoPageRoute,还是PageRouteBuilder,
///它们都继承自PageRoute类,而PageRouteBuilder其实只是PageRoute的一个包装,
///我们可以直接继承PageRoute类来实现自定义路由
class FadeRoute extends PageRoute {
FadeRoute({
@required this.builder,
this.transitionDuration = const Duration(milliseconds: 300),
this.opaque = true,
this.barrierDismissible = false,
this.barrierColor,
this.barrierLabel,
this.maintainState = true,
});
/// 跳转目标widget
final WidgetBuilder builder;
/// 动画时间
@override
final Duration transitionDuration;
/// 是否不透明的
@override
final bool opaque;
@override
final bool barrierDismissible;
/// 屏障的颜色
@override
final Color barrierColor;
/// 屏障的标签
@override
final String barrierLabel;
/// 是否状态保留
@override
final bool maintainState;
@override
Widget buildPage(BuildContext context, Animation<double> animation,
Animation<double> secondaryAnimation) => builder(context);
@override
Widget buildTransitions(BuildContext context, Animation<double> animation,
Animation<double> secondaryAnimation, Widget child) {
return FadeTransition(
//动画效果
opacity: animation,
//跳转目标页面
child: builder(context),
);
}
}
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/router/navigator_utils.dart | Dart | import 'dart:convert';
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:yc_flutter_utils/flutter_utils.dart';
import 'package:yc_flutter_utils/log/log_utils.dart';
import 'package:yc_flutter_utils/router/animation_page_route.dart';
import 'package:yc_flutter_utils/router/animation_type.dart';
/*
* <pre>
* @author yangchong
* blog : https://github.com/yangchong211
* time : 2019/5/30
* desc : 路由简单封装
* revise: 路由几个问题
* 1.如何处理路径配置错误跳转降级操作
* 2.参数的传递,多个参数如何操作
* 3.context有什么作用
* 4.如何统一管理路由,避免混乱
* </pre>
*/
class NavigatorUtils {
/// 解析路由数据并返回map
Map<String, dynamic> parseRoute(String route) {
LogUtils.d('parseRoute: $route');
if (TextUtils.isEmpty(route)){
return null;
}
String routeName = '', jsonData;
if (route.contains('/')) {
routeName = route.substring(0, route.indexOf("/"));
jsonData = route.substring(route.indexOf("/") + 1);
} else {
routeName = route;
}
Map<String, dynamic> data =
jsonData != null ? json.decode("$jsonData") : null;
LogUtils.d('parseRoute: data=$data');
return {'routeName': routeName, 'data': data};
}
/// 从window获取NA传递的路由参数
static Map<String, dynamic> parseRouter(Window window){
// window.defaultRouteName就是获取Android传递过来的参数
// 通过这个字段我们就可以进行Flutter页面的路由的分发
String url = window.defaultRouteName;
// route名称,路由path路径名称
String route = url.indexOf('?') == -1 ? url : url.substring(0, url.indexOf('?'));
// 参数Json字符串
String paramsJson = url.indexOf('?') == -1 ? '{}' : url.substring(url.indexOf('?') + 1);
// 解析参数
Map<String, dynamic> params = json.decode(paramsJson);
LogUtils.d('path---->' + route + " " + params.toString());
params["route"] = route;
return params;
}
// 什么是路由管理???
// 简单俩说,导航管理都会维护一个路由栈,
// 路由入栈(push)操作对应打开一个新页面,
// 路由出栈(pop)操作对应页面关闭操作,
// 而路由管理主要是指如何来管理路由栈。
/// 从根结点跳转页面
static pushGlobal(GlobalKey<NavigatorState> navigatorKey, Widget scene) {
// Another exception was thrown:
// Navigator operation requested with a context that does not include a Navigator.
// 因为flutter会根据这个context一直上溯,一直到根节点的widget,
// 注意,上溯是根据context的,会上溯到这个context相关的widget的最根节点
// 导航到新路由
try {
//执行build方法
var currentState = navigatorKey.currentState;
currentState.push(MaterialPageRoute(
builder: (BuildContext context) => scene,
),);
} catch (e, stack) {
// 有异常时则弹出错误提示
LogUtils.e("路由异常"+e.toString()+"-----"+stack.toString());
}
}
static push(BuildContext context, Widget scene) {
// 第一种方式
// Navigator.of(context).push(new MaterialPageRoute(builder: (context) {
// return new LoginPage();
// }));
// 第二种方式
// Future push = Navigator.push(context, new MaterialPageRoute(builder: (context) {
// return new LoginPage();
// }));
// 简单封装,导航到新路由
Navigator.push(context, MaterialPageRoute(
builder: (BuildContext context) => scene,
),
);
}
/// 跳转页面带动画
/// 采用原生PageRouteBuilder,这个是一个渐变的效果
static pushAnimation(BuildContext context, Widget scene) {
Navigator.push(context, PageRouteBuilder(
//动画时间为500毫秒
transitionDuration: Duration(milliseconds: 500),
pageBuilder: (BuildContext context, Animation animation,
Animation secondaryAnimation) {
return new FadeTransition(
//使用渐隐渐入过渡,
opacity: animation,
//路由页面
child: scene,
);
},
),
);
}
/// 跳转页面带动画
static pushAnimationFade(BuildContext context, Widget scene ) {
Navigator.push(context, FadeRoute(builder: (context) {
return scene;
}));
}
/// 跳转页面带动画,传入type类型
/// type ---> SlideRL 从右到左的滑动
/// type ---> SlideLR 从左到右的滑动
/// type ---> SlideTB 从上到下的滑动
/// type ---> SlideBT 从下到上的滑动
/// type ---> Fade 透明过渡
static pushAnimationType(BuildContext context, Widget scene , AnimationType type) {
AnimationPageRoute route = new AnimationPageRoute(
builder: (context) {
return scene;
},
animationType: type,
);
Navigator.push(context, route);
}
/// 导航到新路由
static pushNamed(BuildContext context,String path) {
// 如何注册路由表,如下所示
// MaterialApp(
// title: 'Flutter Demo',
// initialRoute:"/", //名为"/"的路由作为应用的home(首页)
// theme: ThemeData(
// primarySwatch: Colors.blue,
// ),
// //注册路由表
// routes:{
// "new_page":(context) => NewRoute(),
// "/":(context) => MyHomePage(title: 'Flutter Demo Home Page'), //注册首页路由
// }
// );
// 简单封装,导航到新路由
if(path!=null){
//过路由名称来打开新路由,可以使用Navigator 的pushNamed方法
Navigator.pushNamed(context,path);
}
}
/// 导航到新路由并传入参数
static pushNamedArguments(BuildContext context,String path,{Object arguments}) {
// 简单封装,导航到新路由
if(path!=null){
//过路由名称来打开新路由,可以使用Navigator 的pushNamed方法
Navigator.pushNamed(context,path,arguments: arguments);
}
}
static replace(BuildContext context,Widget old, Widget scene) {
// 简单封装,导航到新路由
// Navigator.replace(context,oldRoute: old,newRoute: scene);
}
static pushAndRemoveUntil(BuildContext context, Widget scene) {
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(
builder: (BuildContext context) => scene,
), (route) => route == null
);
}
/// 跳转新页面并返回结果回调
static pushResult(BuildContext context, Widget scene, Function(Object) function) {
Navigator.push(context, MaterialPageRoute(
builder: (BuildContext context) => scene,
),
).then((result){
// 页面返回result为null
if (result == null){
return;
}
function(result);
}).catchError((error) {
print("$error");
});
}
}
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/screen/screen_utils.dart | Dart |
import 'package:flutter/material.dart';
class ScreenUtils {
static ScreenUtils instance = new ScreenUtils();
//设计稿的设备尺寸修改
double width;
double height;
bool allowFontScaling;
static MediaQueryData _mediaQueryData;
static double _screenWidth;
static double _screenHeight;
//设备的像素密度
static double _pixelRatio;
static double _statusBarHeight;
static double _bottomBarHeight;
static double _textScaleFactor;
ScreenUtils({
this.width = 1080,
this.height = 1920,
this.allowFontScaling = false,
});
static ScreenUtils getInstance() {
return instance;
}
void init(BuildContext context) {
MediaQueryData mediaQuery = MediaQuery.of(context);
_mediaQueryData = mediaQuery;
//当前设备密度比
_pixelRatio = mediaQuery.devicePixelRatio;
//当前设备宽度 dp
_screenWidth = mediaQuery.size.width;
//当前设备高度 dp
_screenHeight = mediaQuery.size.height;
//状态栏高度 dp
_statusBarHeight = mediaQuery.padding.top;
//底部安全区距离 dp
_bottomBarHeight = mediaQuery.padding.bottom;
//每个逻辑像素的字体像素数
_textScaleFactor = mediaQuery.textScaleFactor;
}
static MediaQueryData get mediaQueryData => _mediaQueryData;
///每个逻辑像素的字体像素数,字体的缩放比例
static double get textScaleFactory => _textScaleFactor;
///设备的像素密度
static double get pixelRatio => _pixelRatio;
///当前设备宽度 dp
static double get screenWidthDp => _screenWidth;
///当前设备高度 dp
static double get screenHeightDp => _screenHeight;
///当前设备宽度 px = dp * 密度
static double get screenWidth => _screenWidth * _pixelRatio;
///当前设备高度 px = dp * 密度
static double get screenHeight => _screenHeight * _pixelRatio;
///状态栏高度 dp 刘海屏会更高
static double get statusBarHeight => _statusBarHeight;
///底部安全区距离 dp
static double get bottomBarHeight => _bottomBarHeight;
///实际的dp与设计稿px的比例
get scaleWidth => _screenWidth / instance.width;
get scaleHeight => _screenHeight / instance.height;
///根据设计稿的设备宽度适配
///高度也根据这个来做适配可以保证不变形
setWidth(double width) => width * scaleWidth;
/// 根据设计稿的设备高度适配
/// 当发现设计稿中的一屏显示的与当前样式效果不符合时,
/// 或者形状有差异时,高度适配建议使用此方法
/// 高度适配主要针对想根据设计稿的一屏展示一样的效果
setHeight(double height) => height * scaleHeight;
///字体大小适配方法
///@param fontSize 传入设计稿上字体的px ,
///@param allowFontScaling 控制字体是否要根据系统的“字体大小”辅助选项来进行缩放。默认值为false。
///@param allowFontScaling Specifies whether fonts should scale to respect Text Size accessibility settings. The default is false.
setSp(double fontSize) => allowFontScaling
? setWidth(fontSize)
: setWidth(fontSize) / _textScaleFactor;
}
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/sp/sp_utils.dart | Dart |
import 'dart:convert';
import 'package:http/http.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:yc_flutter_utils/flutter_utils.dart';
import 'package:yc_flutter_utils/extens/extension_map.dart';
import 'package:yc_flutter_utils/extens/extension_list.dart';
/// sp存储工具类,适合存储轻量级数据,不建议存储json长字符串
class SpUtils {
SpUtils._();
static SharedPreferences _prefs;
/// 初始化,必须要初始化
static Future<SharedPreferences> init() async {
if(ObjectUtils.isNull(_prefs)){
_prefs = await SharedPreferences.getInstance();
}
return _prefs;
}
/// 判断是否存在key的数据
static bool hasKey(String key) {
if (_prefs == null){
return false;
}
Set keys = getKeys();
return keys.contains(key);
}
/// put object.
/// 存储object类型数据
static Future<bool> putObject(String key, Object value) {
if (_prefs == null){
return null;
//return Future.value(false);
}
return _prefs.setString(key, value == null ? "" : json.encode(value));
}
/// 获取sp中key的map数据
static Map getObject(String key) {
if (_prefs == null){
return null;
}
String _data = _prefs.getString(key);
return (_data == null || _data.isEmpty) ? null : json.decode(_data);
}
/// put object list.
/// 存储sp中key的list集合
static Future<bool> putObjectList(String key, List<Object> list) {
if (_prefs == null){
return null;
//return Future.value(false);
}
List<String> _dataList = list?.map((value) {
return json.encode(value);
})?.toList();
return _prefs.setStringList(key, _dataList);
}
/// get object list.
/// 获取sp中key的list集合
static List<Map> getObjectList(String key) {
if (_prefs == null){
return null;
}
List<String> dataLis = _prefs.getStringList(key);
return dataLis?.map((value) {
Map _dataMap = json.decode(value);
return _dataMap;
})?.toList();
}
/// get string.
/// 获取sp中key的字符串
static String getString(String key, {String defValue: ''}) {
if (_prefs == null) {
return defValue;
}
return _prefs.getString(key) ?? defValue;
}
/// put string.
/// 存储sp中key的字符串
static Future<bool> putString(String key, String value) {
if (_prefs == null){
return null;
}
return _prefs.setString(key, value);
}
/// get bool.
/// 获取sp中key的布尔值
static bool getBool(String key, {bool defValue: false}) {
if (_prefs == null) {
return defValue;
}
return _prefs.getBool(key) ?? defValue;
}
/// put bool.
/// 存储sp中key的布尔值
static Future<bool> putBool(String key, bool value) {
if (_prefs == null){
return null;
// return Future.value(false);
}
return _prefs.setBool(key, value);
}
/// get int.
/// 获取sp中key的int值
static int getInt(String key, {int defValue: 0}) {
if (_prefs == null) {
return defValue;
}
return _prefs.getInt(key) ?? defValue;
}
/// put int.
/// 存储sp中key的int值
static Future<bool> putInt(String key, int value) {
if (_prefs == null){
return null;
}
return _prefs.setInt(key, value);
}
/// get double.
/// 获取sp中key的double值
static double getDouble(String key, {double defValue: 0.0}) {
if (_prefs == null) {
return defValue;
}
return _prefs.getDouble(key) ?? defValue;
}
/// put double.
/// 存储sp中key的double值
static Future<bool> putDouble(String key, double value) {
if (_prefs == null){
return null;
}
return _prefs.setDouble(key, value);
}
/// get string list.
/// 获取sp中key的list<String>值
static List<String> getStringList(String key,
{List<String> defValue: const []}) {
if (_prefs == null) {
return defValue;
}
return _prefs.getStringList(key) ?? defValue;
}
/// put string list.
/// 存储sp中key的list<String>值
static Future<bool> putStringList(String key, List<String> value) {
if (_prefs == null){
return null;
}
return _prefs.setStringList(key, value);
}
/// 获取sp中key的map值
static Map getStringMap(String key) {
if (_prefs == null){
return null;
}
var jsonString = _prefs.getString(key);
Map map = json.decode(jsonString);
return map;
}
/// 存储sp中key的map值
static Future<bool> putStringMap(String key, Map value) {
if (_prefs == null){
return null;
// return Future.value(false);
}
var jsonMapString = value.toJsonString();
return _prefs.setString(key, jsonMapString);
}
/// 存储sp中key的list值
static Future<bool> putStringList2(String key, List value) {
if (_prefs == null){
return null;
}
var jsonMapString = value.toJsonString();
return _prefs.setString(key, jsonMapString);
}
/// get dynamic.
/// 获取sp中key的dynamic值
static dynamic getDynamic(String key, {Object defValue}) {
if (_prefs == null) {
return defValue;
}
return _prefs.get(key) ?? defValue;
}
/// get keys.
/// 获取sp中所有的key
static Set<String> getKeys() {
if (_prefs == null){
return null;
}
return _prefs.getKeys();
}
/// remove.
/// 移除sp中key的值
static Future<bool> remove(String key) {
if (_prefs == null){
return null;
}
return _prefs.remove(key);
}
/// clear.
/// 清除sp
static Future<bool> clear() {
if (_prefs == null){
return null;
}
return _prefs.clear();
}
///检查初始化
static bool isInitialized() {
return _prefs != null;
}
/// 遍历打印sp的key和value
static void forEach(){
Set<String> keys = getKeys();
Iterator<String> iterator = keys.iterator;
while(iterator.moveNext()){
var key = iterator.current;
var object = get(key);
LogUtils.i("key : $key , value : $object",tag: "SpUtils");
}
}
} | yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/system/system_utils.dart | Dart |
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:yc_flutter_utils/flutter_utils.dart';
/// 系统工具类
class SystemUtils{
/// 拷贝文本内容到剪切板
static bool copyToClipboard(String text, {String successMessage, BuildContext context}) {
if (TextUtils.isNotEmpty(text)) {
Clipboard.setData(new ClipboardData(text: text));
if (context != null) {
Scaffold.of(context)?.showSnackBar(new SnackBar(
duration: Duration(seconds: 1),
content: new Text(successMessage ?? "copy success")));
return true;
} else {
return false;
}
}
return false;
}
/// 隐藏软键盘,具体可看:TextInputChannel
static void hideKeyboard() {
SystemChannels.textInput.invokeMethod('TextInput.hide');
}
/// 展示软键盘,具体可看:TextInputChannel
static void showKeyboard() {
SystemChannels.textInput.invokeMethod('TextInput.show');
}
/// 清除数据
static void clearClientKeyboard() {
SystemChannels.textInput.invokeMethod('TextInput.clearClient');
}
} | yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/text/text_utils.dart | Dart | /// 文本工具类
class TextUtils {
/// 判断文本内容是否为空
static bool isEmpty(String text) {
return text == null || text.isEmpty;
}
/// 判断文本内容是否不为空
static bool isNotEmpty(String text) {
return !isEmpty(text);
}
/// 判断字符串是以xx开头
static bool startsWith(String str, Pattern prefix, [int index = 0]) {
return str != null && str.startsWith(prefix, index);
}
/// 判断一个字符串以任何给定的前缀开始
static bool startsWithAny(String str, List<Pattern> prefixes, [
int index = 0,]) {
return str != null && prefixes.any((prefix) => str.startsWith(prefix, index));
}
/// 判断字符串中是否包含xx
static bool contains(String str, Pattern searchPattern, [int startIndex = 0]){
return str != null && str.contains(searchPattern, startIndex);
}
/// 判断一个字符串是否包含任何给定的搜索模式
static bool containsAny(String str, List<Pattern> searchPatterns, [
int startIndex = 0,]) {
return str != null &&
searchPatterns.any((prefix) => str.contains(prefix, startIndex));
}
/// 使用点缩写字符串
static String abbreviate(String str, int maxWidth, {int offset = 0}) {
if (str == null) {
return null;
} else if (str.length <= maxWidth) {
return str;
} else if (offset < 3) {
return '${str.substring(offset, (offset + maxWidth) - 3)}...';
} else if (maxWidth - offset < 3) {
return '...${str.substring(offset, (offset + maxWidth) - 3)}';
}
return '...${str.substring(offset, (offset + maxWidth) - 6)}...';
}
/// 比较两个字符串是否相同
static int compare(String str1, String str2) {
if (str1 == str2) {
return 0;
}
if (str1 == null || str2 == null) {
return str1 == null ? -1 : 1;
}
return str1.compareTo(str2);
}
/// 比较两个长度一样的字符串有几个字符不同
static int hammingDistance(String str1, String str2) {
if (str1.length != str2.length) {
throw FormatException('Strings must have the same length');
}
var l1 = str1.runes.toList();
var l2 = str2.runes.toList();
var distance = 0;
for (var i = 0; i < l1.length; i++) {
if (l1[i] != l2[i]) {
distance++;
}
}
return distance;
}
/// 每隔 x位 加 pattern。比如用来格式化银行卡
static String formatDigitPattern(String text,
{int digit = 4, String pattern = ' '}) {
text = text.replaceAllMapped(RegExp('(.{$digit})'), (Match match) {
return '${match.group(0)}$pattern';
});
if (text.endsWith(pattern)) {
text = text.substring(0, text.length - 1);
}
return text;
}
/// 每隔 x位 加 pattern, 从末尾开始
static String formatDigitPatternEnd(String text,
{int digit = 4, String pattern = ' '}) {
String temp = reverse(text);
temp = formatDigitPattern(temp, digit: digit, pattern: pattern);
temp = reverse(temp);
return temp;
}
/// 每隔4位加空格
static String formatSpace4(String text) {
return formatDigitPattern(text);
}
/// 每隔3三位加逗号
/// num 数字或数字字符串。int型。
static String formatComma3(Object num) {
return formatDigitPatternEnd(num.toString(), digit: 3, pattern: ',');
}
/// 每隔3三位加逗号
/// num 数字或数字字符串。double型。
static String formatDoubleComma3(Object num,
{int digit = 3, String pattern = ','}) {
List<String> list = num.toString().split('.');
String left =
formatDigitPatternEnd(list[0], digit: digit, pattern: pattern);
String right = list[1];
return '$left.$right';
}
/// 隐藏手机号中间n位
static String hideNumber(String phoneNo,
{int start = 3, int end = 7, String replacement = '****'}) {
return phoneNo.replaceRange(start, end, replacement);
}
/// 替换字符串中的数据
static String replace(String text, Pattern from, String replace) {
return text.replaceAll(from, replace);
}
/// 按照正则切割字符串
static List<String> split(String text, Pattern pattern) {
return text.split(pattern);
}
/// 反转字符串
static String reverse(String text) {
if (isEmpty(text)){
return '';
}
StringBuffer sb = StringBuffer();
for (int i = text.length - 1; i >= 0; i--) {
var codeUnitAt = text.codeUnitAt(i);
sb.writeCharCode(codeUnitAt);
}
return sb.toString();
}
String currencyFormat(int money) {
if (money == null) {
return "";
}
String moneyStr = money.toString();
String finalStr = "";
int groupSize = 3;
int oddNumberLength = moneyStr.length -
(moneyStr.length ~/ groupSize) * groupSize;
if (oddNumberLength > 0) {
finalStr += moneyStr.substring(0, oddNumberLength);
if (moneyStr.length > groupSize) {
finalStr += ",";
}
}
for (int i = oddNumberLength; i < moneyStr.length; i += groupSize) {
finalStr += moneyStr.substring(i, i + groupSize);
if (i + groupSize < moneyStr.length - 1) {
finalStr += ",";
}
}
return finalStr;
}
}
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/time/abs_time_info.dart | Dart |
/// Timeline information configuration.
/// Timeline信息配置.
abstract class AbsTimelineInfo {
String suffixAgo(); //suffix ago(后缀 后).
String suffixAfter(); //suffix after(后缀 前).
int maxJustNowSecond() => 30; // max just now second.
String lessThanOneMinute() => ''; //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 weeks(int week) => ''; //x week(星期x).
String days(int days); //x days(x天).
}
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/time/day_format.dart | Dart |
/// (xx)Configurable output.
/// (xx)为可配置输出.
enum DayFormat {
/// (less than 10s->just now)、x minutes、x hours、(Yesterday)、x days.
/// (小于10s->刚刚)、x分钟、x小时、(昨天)、x天.
Simple,
/// (less than 10s->just now)、x minutes、x hours、[This year:(Yesterday/a day ago)、(two days age)、MM-dd ]、[past years: yyyy-MM-dd]
/// (小于10s->刚刚)、x分钟、x小时、[今年: (昨天/1天前)、(2天前)、MM-dd],[往年: yyyy-MM-dd].
Common,
/// 日期 + HH:mm
/// (less than 10s->just now)、x minutes、x hours、[This year:(Yesterday HH:mm/a day ago)、(two days age)、MM-dd HH:mm]、[past years: yyyy-MM-dd HH:mm]
/// 小于10s->刚刚)、x分钟、x小时、[今年: (昨天 HH:mm/1天前)、(2天前)、MM-dd HH:mm],[往年: yyyy-MM-dd HH:mm].
Full,
} | yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/time/en_info_impl.dart | Dart |
import 'package:yc_flutter_utils/time/abs_time_info.dart';
class EnInfo implements AbsTimelineInfo {
String suffixAgo() => ' ago';
String suffixAfter() => ' after';
int maxJustNowSecond() => 30;
String lessThanOneMinute() => 'just now';
String customYesterday() => 'Yesterday';
bool keepOneDay() => true;
bool keepTwoDays() => true;
String oneMinute(int minutes) => 'a minute';
String minutes(int minutes) => '$minutes minutes';
String anHour(int hours) => 'an hour';
String hours(int hours) => '$hours hours';
String oneDay(int days) => 'a day';
String weeks(int week) => ''; //x week(星期x).
String days(int days) => '$days days';
}
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/time/en_normal_info_impl.dart | Dart |
import 'package:yc_flutter_utils/time/abs_time_info.dart';
class EnNormalInfo implements AbsTimelineInfo {
String suffixAgo() => ' ago';
String suffixAfter() => ' after';
int maxJustNowSecond() => 30;
String lessThanOneMinute() => 'just now';
String customYesterday() => 'Yesterday';
bool keepOneDay() => true;
bool keepTwoDays() => false;
String oneMinute(int minutes) => 'a minute';
String minutes(int minutes) => '$minutes minutes';
String anHour(int hours) => 'an hour';
String hours(int hours) => '$hours hours';
String oneDay(int days) => 'a day';
String weeks(int week) => ''; //x week(星期x).
String days(int days) => '$days days';
}
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/time/time_utils.dart | Dart |
import 'package:yc_flutter_utils/date/date_utils.dart';
import 'package:yc_flutter_utils/time/abs_time_info.dart';
import 'package:yc_flutter_utils/time/day_format.dart';
import 'package:yc_flutter_utils/time/en_info_impl.dart';
import 'package:yc_flutter_utils/time/en_normal_info_impl.dart';
import 'package:yc_flutter_utils/time/zh_info_impl.dart';
import 'package:yc_flutter_utils/time/zh_normal_info_impl.dart';
Map<String, AbsTimelineInfo> _timelineInfoMap = {
'zh': ZhInfo(),
'en': EnInfo(),
'zh_normal': ZhNormalInfo(),
'en_normal': EnNormalInfo(),
};
/// add custom configuration.
void setLocaleInfo(String locale, AbsTimelineInfo timelineInfo) {
ArgumentError.checkNotNull(locale, '[locale] must not be null');
ArgumentError.checkNotNull(timelineInfo, '[timelineInfo] must not be null');
_timelineInfoMap[locale] = timelineInfo;
}
/// 时间轴工具类
class TimeUtils {
/// format time by DateTime.
/// dateTime
/// locDateTime: current time or schedule time.
/// locale: output key.
static String formatByDateTime(
DateTime dateTime, {
DateTime locDateTime,
String locale,
DayFormat dayFormat,
}) {
return format(
dateTime.millisecondsSinceEpoch,
locTimeMs: locDateTime?.millisecondsSinceEpoch,
locale: locale,
dayFormat: dayFormat,
);
}
/// format time by millis.
/// dateTime : millis.
/// locDateTime: current time or schedule time. millis.
/// locale: output key.
static String format(
int ms, {
int locTimeMs,
String locale,
DayFormat dayFormat,
}) {
int _locTimeMs = locTimeMs ?? DateTime.now().millisecondsSinceEpoch;
String _locale = locale ?? 'en';
AbsTimelineInfo _info = _timelineInfoMap[_locale] ?? EnInfo();
DayFormat _dayFormat = dayFormat ?? DayFormat.Common;
int elapsed = _locTimeMs - ms;
String suffix;
if (elapsed < 0) {
suffix = _info.suffixAfter();
// suffix after is empty. user just now.
if (suffix.isNotEmpty) {
elapsed = elapsed.abs();
_dayFormat = DayFormat.Simple;
} else {
return _info.lessThanOneMinute();
}
} else {
suffix = _info.suffixAgo();
}
String timeline;
if (_info.customYesterday().isNotEmpty &&
DateUtils.isYesterdayByMilliseconds(ms, _locTimeMs)) {
return _getYesterday(ms, _info, _dayFormat);
}
if (!DateUtils.yearIsEqualByMilliseconds(ms, _locTimeMs)) {
timeline = _getYear(ms, _dayFormat);
if (timeline.isNotEmpty) return timeline;
}
final num seconds = elapsed / 1000;
final num minutes = seconds / 60;
final num hours = minutes / 60;
final num days = hours / 24;
if (seconds < 90) {
timeline = _info.oneMinute(1);
if (suffix != _info.suffixAfter() &&
_info.lessThanOneMinute().isNotEmpty &&
seconds < _info.maxJustNowSecond()) {
timeline = _info.lessThanOneMinute();
suffix = '';
}
} else if (minutes < 60) {
timeline = _info.minutes(minutes.round());
} else if (minutes < 90) {
timeline = _info.anHour(1);
} else if (hours < 24) {
timeline = _info.hours(hours.round());
} else {
if ((days.round() == 1 && _info.keepOneDay() == true) ||
(days.round() == 2 && _info.keepTwoDays() == true)) {
_dayFormat = DayFormat.Simple;
}
timeline = _formatDays(ms, days.round(), _info, _dayFormat);
suffix = (_dayFormat == DayFormat.Simple ? suffix : '');
}
return timeline + suffix;
}
/// Timeline like QQ.
///
/// today (HH:mm)
/// yesterday (昨天;Yesterday)
/// this week (星期一,周一;Monday,Mon)
/// others (yyyy-MM-dd)
static String formatA(
int ms, {
int locMs,
String formatToday = 'HH:mm',
String format = 'yyyy-MM-dd',
String languageCode = 'en',
bool short = false,
}) {
int _locTimeMs = locMs ?? DateTime.now().millisecondsSinceEpoch;
int elapsed = _locTimeMs - ms;
if (elapsed < 0) {
return DateUtils.formatDateMilliseconds(ms, format: formatToday);
}
if (DateUtils.isToday(ms, locMs: _locTimeMs)) {
return DateUtils.formatDateMilliseconds(ms, format: formatToday);
}
if (DateUtils.isYesterdayByMilliseconds(ms, _locTimeMs)) {
return languageCode == 'zh' ? '昨天' : 'Yesterday';
}
if (DateUtils.isWeek(ms, locMs: _locTimeMs)) {
return DateUtils.getWeekdayByMilliseconds(ms,
languageCode: languageCode, short: short);
}
return DateUtils.formatDateMilliseconds(ms, format: format);
}
/// get Yesterday.
/// 获取昨天.
static String _getYesterday(
int ms,
AbsTimelineInfo info,
DayFormat dayFormat,
) {
return info.customYesterday() +
(dayFormat == DayFormat.Full
? (' ' + DateUtils.formatDateMilliseconds(ms, format: 'HH:mm'))
: '');
}
/// get is not year info.
/// 获取非今年信息.
static String _getYear(
int ms,
DayFormat dayFormat,
) {
if (dayFormat != DayFormat.Simple) {
return DateUtils.formatDateMilliseconds(ms,
format: (dayFormat == DayFormat.Common
? 'yyyy-MM-dd'
: 'yyyy-MM-dd HH:mm'));
}
return '';
}
/// format Days.
static String _formatDays(
int ms,
num days,
AbsTimelineInfo info,
DayFormat dayFormat,
) {
String timeline;
switch (dayFormat) {
case DayFormat.Simple:
timeline = (days == 1 ? info.customYesterday().isEmpty
? info.oneDay(days.round()) : info.days(2)
: info.days(days.round()));
break;
case DayFormat.Common:
timeline = DateUtils.formatDateMilliseconds(ms, format: 'MM-dd');
break;
case DayFormat.Full:
timeline = DateUtils.formatDateMilliseconds(ms, format: 'MM-dd HH:mm');
break;
}
return timeline;
}
}
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/time/zh_info_impl.dart | Dart |
import 'package:yc_flutter_utils/time/abs_time_info.dart';
class ZhInfo implements AbsTimelineInfo {
String suffixAgo() => '前';
String suffixAfter() => '后';
int maxJustNowSecond() => 30;
String lessThanOneMinute() => '刚刚';
String customYesterday() => '昨天';
bool keepOneDay() => true;
bool keepTwoDays() => true;
String oneMinute(int minutes) => '$minutes分钟';
String minutes(int minutes) => '$minutes分钟';
String anHour(int hours) => '$hours小时';
String hours(int hours) => '$hours小时';
String oneDay(int days) => '$days天';
String weeks(int week) => ''; //x week(星期x).
String days(int days) => '$days天';
}
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/time/zh_normal_info_impl.dart | Dart |
import 'package:yc_flutter_utils/time/abs_time_info.dart';
class ZhNormalInfo implements AbsTimelineInfo {
String suffixAgo() => '前';
String suffixAfter() => '后';
int maxJustNowSecond() => 30;
String lessThanOneMinute() => '刚刚';
String customYesterday() => '昨天';
bool keepOneDay() => true;
bool keepTwoDays() => false;
String oneMinute(int minutes) => '$minutes分钟';
String minutes(int minutes) => '$minutes分钟';
String anHour(int hours) => '$hours小时';
String hours(int hours) => '$hours小时';
String oneDay(int days) => '$days天';
String weeks(int week) => ''; //x week(星期x).
String days(int days) => '$days天';
} | yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/timer/task_queue_utils.dart | Dart | import 'dart:async';
import 'dart:collection';
import 'package:yc_flutter_utils/log/log_utils.dart';
/// 队列task工具类
class TaskQueueUtils {
//队列任务
Queue<_TaskInfo> _taskList = Queue();
//是否有正在进行的task
_TaskInfo _currentTask;
void addTask(Future Function() performSelector , int max) {
//最多max个任务
if (_taskList.length >= max) {
//大于max个后,从头开始删除、保持队列任务是最新的。
LogUtils.d("TripQueueUtil - 移除队列");
_taskList.removeFirst();
}
_TaskInfo taskInfo = _TaskInfo(performSelector);
/// 添加到任务队列
LogUtils.d("TripQueueUtil - 加入队列");
_taskList.add(taskInfo);
/// 触发任务
_doTask();
}
void cancelTasks() {
_taskList.clear();
_currentTask = null;
}
_doTask() async {
if (_currentTask != null) return;
if (_taskList.isEmpty) return;
LogUtils.d("TripQueueUtil -出队列取任务");
_currentTask = _taskList.removeFirst();
/// 执行任务
LogUtils.d("TripQueueUtil - 执行任务");
await _currentTask.performSelector();
_currentTask = null;
/// 递归执行任务
_doTask();
}
}
class _TaskInfo {
Future Function() performSelector;
_TaskInfo(this.performSelector);
}
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/timer/timer_utils.dart | Dart | import 'dart:async';
///timer callback.(millisUntilFinished 毫秒).
typedef void OnTimerTickCallback(int millisUntilFinished);
/// 倒计时timer工具类
class TimerUtils {
TimerUtils({
this.mInterval = Duration.millisecondsPerSecond,
this.mTotalTime = 0
});
/// Timer.
Timer _mTimer;
/// Is Timer active.
/// Timer是否启动.
bool _isActive = false;
/// Timer interval (unit millisecond,def: 1000 millisecond).
/// Timer间隔 单位毫秒,默认1000毫秒(1秒).
int mInterval;
/// countdown totalTime.
/// 倒计时总时间
/// 单位毫秒
int mTotalTime;
OnTimerTickCallback _onTimerTickCallback;
/// set Timer interval. (unit millisecond).
/// 设置Timer间隔.
void setInterval(int interval) {
if (interval <= 0) interval = Duration.millisecondsPerSecond;
mInterval = interval;
}
/// set countdown totalTime. (unit millisecond).
/// 设置倒计时总时间.
void setTotalTime(int totalTime) {
if (totalTime <= 0) return;
mTotalTime = totalTime;
}
/// start Timer.
/// 启动定时Timer.
void startTimer() {
if (_isActive || mInterval <= 0) return;
_isActive = true;
Duration duration = Duration(milliseconds: mInterval);
_doCallback(0);
_mTimer = Timer.periodic(duration, (Timer timer) {
_doCallback(timer.tick);
});
}
/// start countdown Timer.
/// 启动倒计时Timer.
void startCountDown() {
if (_isActive || mInterval <= 0 || mTotalTime <= 0) return;
_isActive = true;
Duration duration = Duration(milliseconds: mInterval);
_doCallback(mTotalTime);
_mTimer = Timer.periodic(duration, (Timer timer) {
int time = mTotalTime - mInterval;
mTotalTime = time;
if (time >= mInterval) {
_doCallback(time);
} else if (time == 0) {
_doCallback(time);
cancel();
} else {
timer.cancel();
Future.delayed(Duration(milliseconds: time), () {
mTotalTime = 0;
_doCallback(0);
cancel();
});
}
});
}
void _doCallback(int time) {
if (_onTimerTickCallback != null) {
_onTimerTickCallback(time);
}
}
/// update countdown totalTime.
/// 重设倒计时总时间.
void updateTotalTime(int totalTime) {
cancel();
mTotalTime = totalTime;
startCountDown();
}
/// timer is Active.
/// 判断Timer是否启动.
bool isActive() {
return _isActive;
}
/// 暂停计时器
void pauseTimer(){
}
/// Cancels the timer.
/// 取消计时器.
void cancel() {
_mTimer?.cancel();
_mTimer = null;
_isActive = false;
}
/// set timer callback.
/// 设置倒计时器的监听
void setOnTimerTickCallback(OnTimerTickCallback callback) {
_onTimerTickCallback = callback;
}
}
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/toast/snack_utils.dart | Dart |
import 'package:flutter/material.dart';
/// SnackBar工具类
class SnackUtils{
/// 吐司弹出SnackBar
static toast(BuildContext context, String msg,
{duration = const Duration(milliseconds: 600),
Color color, SnackBarAction action}) {
Scaffold.of(context).showSnackBar(SnackBar(
content: Text(msg),
duration: duration,
action: action,
backgroundColor: color??Theme.of(context).primaryColor,
));
}
} | yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/utils/enum_utils.dart | Dart | /// 枚举工具类
class EnumUtils {
///枚举格式化 String
static String enumValueToString(Object o){
var last = o.toString().split('.').last;
return last;
}
///String反显枚举
static T enumValueFromString<T>(String key, List<T> values) =>
values.firstWhere((v) => key == enumValueToString(v), orElse: () => null);
}
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/utils/flutter_init_utils.dart | Dart |
/// 初始化工具类
class FlutterInitUtils {
///初始化操作
static Future<void> fetchInitUtils() async {
}
} | yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/utils/platform_utils.dart | Dart | library platform_utils;
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
/// 平台获取类型工具类
class PlatformUtils {
/// 返回值或运行基于平台的函数。
/// 如果传递了上下文,它将通过 Theme.of(context).platform 获取平台。
/// 否则,它将使用 defaultTargetPlatform。
static get({BuildContext context}) {
return context != null ? Theme.of(context).platform : defaultTargetPlatform;
}
static T select<T>({BuildContext context, dynamic android, dynamic ios,
dynamic fuchsia, dynamic web, dynamic macOS,dynamic windows,
dynamic linux,dynamic defaultWhenNull}) {
var func;
if (kIsWeb) {
func = web;
} else {
func = {
TargetPlatform.iOS: ios,
TargetPlatform.android: android,
TargetPlatform.fuchsia: fuchsia,
TargetPlatform.macOS: macOS,
TargetPlatform.windows: windows,
TargetPlatform.linux: linux,
}[get(context: context)];
}
if (func is Function) {
return func();
}
if (func == null && defaultWhenNull is Function) {
return defaultWhenNull();
}
return func ?? defaultWhenNull;
}
}
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/utils/random_utils.dart | Dart | library randomutils;
import 'dart:math';
import 'package:yc_flutter_utils/flutter_utils.dart';
Random _random = Random();
/// 随机工具类
class RandomUtils {
/// Generates a random integer that represents a Hex color.
/// 生成一个表示十六进制颜色的随机整数
static int randomColor() {
var hex = "0xFF";
for (int i = 0; i < 3; i++) {
hex += _random.nextInt(255).toRadixString(16).padLeft(2, '0');
}
return int.parse(hex);
}
/// Generates a random string of provided or random length.
/// 生成指定长度或随机长度的随机字符串
static String randomString({int length}) {
var codeUnits =
List.generate(length ?? _random.nextInt(pow(2, 10)), (index) {
return _random.nextInt(33) + 89;
});
return String.fromCharCodes(codeUnits);
}
/// Cleans up provided string by removing extra whitespace.
/// 通过删除额外的空格来清理提供的字符串
static String condenseWhiteSpace(String str) {
return str.replaceAll(RegExp(r"\s+"), " ").trim();
}
/// Removes all whitespace from provided string.
/// 从提供的字符串中删除所有空格。
static String removeWhiteSpace(String str) {
return str.replaceAll(RegExp(r"\s+"), "");
}
/// Returns true for for all strings that are empty, null or only whitespace.
/// 对于所有为空、空或只有空格的字符串返回true。
static bool isWhiteSpaceOrEmptyOrNull(String str) {
return removeWhiteSpace(str ?? "").isEmpty;
}
/// Extracts decimal numbers from the provided string.
/// 从提供的字符串中提取十进制数。
static String removeNonDigits(String str) {
return str.replaceAll(RegExp(r"\D"), "");
}
/// Generate a random number between start and end inclusive.
/// 在开始和结束之间生成一个随机数
static int randInt(int end, {int start = 0}) {
return _random.nextInt(end) + start;
}
/// 从列表中返回一个随机元素。
static T randomElement<T>(List<T> items) {
if(ObjectUtils.isEmpty(items)){
return null;
}
return items[randInt(items.length)];
}
}
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/widget/widget_utils.dart | Dart |
class WidgetUtils{
} | yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
lib/yc_flutter_utils.dart | Dart |
import 'dart:async';
import 'package:flutter/services.dart';
class YcFlutterUtils {
static const MethodChannel _channel =
const MethodChannel('yc_flutter_utils');
static Future<String> get platformVersion async {
final String version = await _channel.invokeMethod('getPlatformVersion');
return version;
}
}
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
test/yc_flutter_utils_test.dart | Dart | import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:yc_flutter_utils/yc_flutter_utils.dart';
void main() {
const MethodChannel channel = MethodChannel('yc_flutter_utils');
TestWidgetsFlutterBinding.ensureInitialized();
setUp(() {
channel.setMockMethodCallHandler((MethodCall methodCall) async {
return '42';
});
});
tearDown(() {
channel.setMockMethodCallHandler(null);
});
test('getPlatformVersion', () async {
expect(await YcFlutterUtils.platformVersion, '42');
});
}
| yangchong211/YCFlutterUtils | 255 | Flutter Utils 全网最齐全的工具类。包含bus,颜色,日期,文件,json,log,sp,加解密,num,图片,网络,正则,验证,路由,文本,时间,spi,计时器,拓展类,编解码,发射,异常,字节转化,解析等等工具类。 | Dart | yangchong211 | 杨充 | Tencent |
AppJni/build.gradle | Gradle | apply plugin: 'com.android.application'
android {
compileSdkVersion 29
buildToolsVersion "29.0.0"
defaultConfig {
applicationId "com.yc.jnidemo"
minSdkVersion 17
targetSdkVersion 29
versionCode 1
versionName "1.0"
ndk {
// Specifies the ABI configurations of your native
// libraries Gradle should build and package with your APK.
abiFilters 'armeabi-v7a', 'arm64-v8a', 'x86', 'x86_64'
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
externalNativeBuild {
cmake {
path "src/main/cpp/CMakeLists.txt"
version "3.10.2"
}
}
//列出所有包含有so文件的库信息,主要是找到项目中so库在那个项目文件夹下
tasks.whenTaskAdded { task ->
//如果是有多个flavor,则用 mergeFlavorDebugNativeLibs的形式
if (task.name=='mergeDebugNativeLibs') {
task.doFirst {
println("------------------- find so files start -------------------")
println("------------------- find so files start -------------------")
println("------------------- find so files start -------------------")
it.inputs.files.each { file ->
printDir(new File(file.absolutePath))
}
println("------------------- find so files end -------------------")
println("------------------- find so files end -------------------")
println("------------------- find so files end -------------------")
}
}
}
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'androidx.annotation:annotation:1.1.0'
implementation 'androidx.recyclerview:recyclerview:1.0.0'
implementation 'androidx.cardview:cardview:1.0.0'
implementation "com.google.android:flexbox:0.3.0"
implementation 'androidx.constraintlayout:constraintlayout:2.0.2'
// implementation project(':MoonerJniLib')
implementation project(':CallJniLib')
implementation project(':TestJniLib')
implementation project(':SafetyJniLib')
implementation project(':SignalHooker')
implementation project(':CrashDumper')
//implementation project(':EpicJniLib')
}
def printDir(File file) {
if (file != null) {
if (file.isDirectory()) {
file.listFiles().each {
printDir(it)
}
} else if (file.absolutePath.endsWith(".so")) {
println "find so file: $file.absolutePath"
}
}
}
| yangchong211/YCJniHelper | 283 | JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例 | Java | yangchong211 | 杨充 | Tencent |
AppJni/src/main/cpp/test_crash.cpp | C++ | #include <jni.h>
#include <string>
void raiseError(int signal) {
raise(signal);
}
extern "C"
JNIEXPORT void JNICALL
Java_com_yc_jnidemo_CrashActivity_nativeCrash(JNIEnv *env, jobject thiz) {
raiseError(SIGABRT);
} | yangchong211/YCJniHelper | 283 | JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例 | Java | yangchong211 | 杨充 | Tencent |
AppJni/src/main/java/com/yc/jnidemo/CrashActivity.java | Java | package com.yc.jnidemo;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.RadioGroup;
import android.widget.TextView;
import com.yc.crash.NativeCrashDumper;
import com.yc.crash.NativeHandleMode;
import com.yc.crash.NativeCrashListener;
import java.io.FileInputStream;
import java.io.IOException;
public class CrashActivity extends AppCompatActivity implements RadioGroup.OnCheckedChangeListener {
static {
System.loadLibrary("test_crash");
}
private static final String TAG = "MainActivity : ";
public native void nativeCrash();
private RadioGroup radioGroup;
private TextView tvCrashLog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_crash);
initView();
}
private void initView() {
tvCrashLog = findViewById(R.id.tv_crash_log);
radioGroup = findViewById(R.id.rg_handle_mode);
radioGroup.setOnCheckedChangeListener(this);
findViewById(R.id.btn_crash).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
crash(v);
}
});
}
public void crash(View view) {
nativeCrash();
}
private String readContentFromFile(String path) {
FileInputStream fis = null;
try {
fis = new FileInputStream(path);
byte[] data = new byte[fis.available()];
fis.read(data);
fis.close();
return new String(data);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
NativeHandleMode handleMode;
switch (checkedId){
case R.id.rb_notice_callback:
handleMode = NativeHandleMode.NOTICE_CALLBACK;
break;
case R.id.rb_raise_error:
handleMode = NativeHandleMode.RAISE_ERROR;
break;
case R.id.rb_do_nothing:
default:
handleMode = NativeHandleMode.DO_NOTHING;
break;
}
boolean init = NativeCrashDumper.getInstance().init(getFilesDir().getAbsolutePath(), new NativeCrashListener() {
@Override
public void onSignalReceived(int signal, final String logPath) {
final String content = readContentFromFile(logPath);
Log.i(TAG, "onSignalReceived: " + content);
runOnUiThread(new Runnable() {
@Override
public void run() {
tvCrashLog.setText(content);
}
});
}
}, handleMode);
}
}
| yangchong211/YCJniHelper | 283 | JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例 | Java | yangchong211 | 杨充 | Tencent |
AppJni/src/main/java/com/yc/jnidemo/EpicActivity.java | Java | package com.yc.jnidemo;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
public class EpicActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
// public static void findAndHookMethod() {
// try {
// Class<?> targetClass = TelephonyManager.class;
// String targetMethod = "getDeviceId";
// Object[] paramsWithDefaultHandler = {int.class};
// //核心方法
// DexposedBridge.findAndHookMethod(targetClass, targetMethod, paramsWithDefaultHandler);
// //核心方法
// DexposedBridge.findAndHookMethod(targetClass, targetMethod, new XC_MethodHook() {
// @Override
// protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
// super.beforeHookedMethod(param);
// }
//
// @Override
// protected void afterHookedMethod(MethodHookParam param) throws Throwable {
// super.afterHookedMethod(param);
// }
// });
// } catch (NoSuchMethodError error) {
// error.printStackTrace();
// }
// }
}
| yangchong211/YCJniHelper | 283 | JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例 | Java | yangchong211 | 杨充 | Tencent |
AppJni/src/main/java/com/yc/jnidemo/MainActivity.java | Java | package com.yc.jnidemo;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.yc.calljni.CallNativeLib;
import com.yc.safetyjni.SafetyJniLib;
import com.yc.signalhooker.ILogger;
import com.yc.signalhooker.ISignalListener;
import com.yc.signalhooker.SigQuitHooker;
import com.yc.testjnilib.NativeLib;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private TextView tv2;
private TextView tv4;
private TextView tv5;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
//initSignal();
}
private void initSignal() {
SigQuitHooker.initSignalHooker();
SigQuitHooker.setSignalListener(new ISignalListener() {
@Override
public void onReceiveAnrSignal() {
Log.d("SigQuitHooker: " , "onReceiveAnrSignal: do" );
}
});
SigQuitHooker.setLogger(new ILogger() {
@Override
public void onPrintLog(String message) {
Log.d("SigQuitHooker: " , "message: " + message);
}
});
}
private void init() {
findViewById(R.id.tv_1).setOnClickListener(this);
findViewById(R.id.tv_3).setOnClickListener(this);
tv2 = findViewById(R.id.tv_2);
tv4 = findViewById(R.id.tv_4);
tv5 = findViewById(R.id.tv_5);
tv5.setOnClickListener(this);
}
@SuppressLint("SetTextI18n")
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.tv_1:
String fromJNI = NativeLib.getInstance().stringFromJNI();
String md5 = NativeLib.getInstance().getMd5("yc");
NativeLib.getInstance().initLib("db");
String stringFromJNI = SafetyJniLib.getInstance().stringFromJNI();
String nameFromJNI = NativeLib.getInstance().getNameFromJNI();
tv2.setText("java调用c/c++:" + nameFromJNI);
break;
case R.id.tv_3:
CallNativeLib.getInstance().callJavaField("com/yc/calljni/HelloCallBack","name");
CallNativeLib.getInstance().callJavaMethod("com/yc/calljni/HelloCallBack","updateName");
tv4.setText("这个就看日志打印");
break;
case R.id.tv_5:
startActivity(new Intent(this, CrashActivity.class));
break;
default:
break;
}
}
}
| yangchong211/YCJniHelper | 283 | JNI学习案例,通过简单的案例快速入门jni开发。JNI基础语法介绍,so库生成打包和反编译,Java和C/C++相关调用案例 | Java | yangchong211 | 杨充 | Tencent |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.