YSTools.dart 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931
  1. import 'dart:convert';
  2. import 'dart:io';
  3. import 'dart:math';
  4. import 'package:cached_network_image/cached_network_image.dart';
  5. import 'package:flutter/foundation.dart';
  6. import 'package:flutter/material.dart';
  7. import 'package:flutter/services.dart';
  8. import 'package:flutter_screenutil/flutter_screenutil.dart';
  9. import 'package:flutter_wallet/generated/l10n.dart';
  10. import 'package:flutter_wallet/tools/YSBip.dart';
  11. import 'package:flutter_wallet/tools/YSNetWork.dart';
  12. import 'package:intl/intl.dart';
  13. import 'package:path_provider/path_provider.dart';
  14. import 'package:permission_handler/permission_handler.dart';
  15. import 'dart:math' as math;
  16. import 'package:provider/provider.dart';
  17. import 'package:local_auth/local_auth.dart';
  18. import 'package:local_auth_android/local_auth_android.dart';
  19. import 'package:local_auth_ios/local_auth_ios.dart';
  20. import 'package:qr_flutter/qr_flutter.dart';
  21. import 'package:qrscan/qrscan.dart' as scanner;
  22. import 'package:shared_preferences/shared_preferences.dart';
  23. import 'package:web3dart/credentials.dart';
  24. import 'YSAlertView.dart';
  25. import 'YSSqflite.dart';
  26. enum FillInType{
  27. choose,
  28. input,
  29. none,
  30. file,
  31. }
  32. double ysHeight(BuildContext context) => MediaQuery.of(context).size.height;
  33. double ysWidth(BuildContext context) => MediaQuery.of(context).size.width;
  34. double ysTOP(BuildContext context) => MediaQuery.of(context).padding.top;
  35. double ysBottom(BuildContext context) => MediaQuery.of(context).padding.bottom;
  36. double ystabBarHeight = 70;
  37. String accessToken = "sk.eyJ1IjoiYmxvY2tjYXJib24iLCJhIjoiY2xrcm81enRyMmx6dTNra2VhZnMwcmNneCJ9.inGPH4-QFL6UX1NsDHKeiA";
  38. hsp(int number){
  39. return ScreenUtil().setHeight(number);
  40. }
  41. zsp(int number){
  42. return ScreenUtil().setSp(number);
  43. }
  44. ///手机号验证
  45. bool isChinaPhoneLegal(String str) {
  46. return RegExp(r"^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\d{8}$").hasMatch(str);
  47. }
  48. ///邮箱验证
  49. bool isEmail(String str) {
  50. return RegExp(r"^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$").hasMatch(str);
  51. }
  52. ///验证URL
  53. bool isUrl(String value) {
  54. return RegExp(r"^((https|http|ftp|rtsp|mms)?:\/\/)[^\s]+").hasMatch(value);
  55. }
  56. ///验证数字
  57. bool isNumber(String value) {
  58. return RegExp(r'^-?[0-9.]+$').hasMatch(value);
  59. }
  60. ///验证车牌
  61. bool isCarNumber(String value) {
  62. ////1、这条正则可以校验 普通汽车的车牌、新能源客(货)车车牌
  63. // const carNoReg = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}(([A-Z0-9]{4}[A-Z0-9挂学警港澳]{1}$)|([0-9]{5}[DF]$)|([DF][A-HJ-NP-Z0-9][0-9]{4}$))/; //普通车牌 | 新能源货车 | 新能源小客车 车牌校验规则
  64. // //2、普通车车牌校验
  65. // const carCardP = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳]{1}$/;
  66. // //3、新能源车牌校验
  67. // const carCardD = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}(([0-9]{5}[DF]$)|([DF][A-HJ-NP-Z0-9][0-9]{4}$))/;
  68. // //4、农用车辆及拖拉机车牌号验证:
  69. // const carCardD = /^(([\u4e00-\u9fa5][a-zA-Z]|[\u4e00-\u9fa5]{2}\d{2}|[\u4e00-\u9fa5]{2}[a-zA-Z])[-]?|([wW][Jj][\u4e00-\u9fa5]{1}[-]?)|([a-zA-Z]{2}))([A-Za-z0-9]{5}|[DdFf][A-HJ-NP-Za-hj-np-z0-9][0-9]{4}|[0-9]{5}[DdFf])$/
  70. return RegExp(r"^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}(([A-Z0-9]{4}[A-Z0-9挂学警港澳]{1}$)|([0-9]{5}[DF]$)|([DF][A-HJ-NP-Z0-9][0-9]{4}$))").hasMatch(value);
  71. }
  72. ///验证中文
  73. bool isChinese(String value) {
  74. return RegExp(r"[\u4e00-\u9fa5]").hasMatch(value);
  75. }
  76. ///验证身份证
  77. bool isIdCard(String value) {
  78. return RegExp(r"\d{17}[\d|x]|\d{15}").hasMatch(value);
  79. }
  80. bool isPassword(String value) {
  81. return RegExp(r"(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.{7,})\w+").hasMatch(value);
  82. }
  83. class LogUtil {
  84. static const _separator = "=";
  85. static const _split =
  86. "$_separator$_separator$_separator$_separator$_separator$_separator$_separator$_separator$_separator";
  87. static const _title = "Yl-Log";
  88. static const _isDebug = true;
  89. static const int _limitLength = 800;
  90. static const String _startLine = "$_split$_title$_split";
  91. static const String _endLine = "$_split$_separator$_separator$_separator$_split";
  92. //仅Debug模式可见
  93. static void d(dynamic obj) {
  94. if (_isDebug) {
  95. _log(obj.toString());
  96. }
  97. }
  98. static void v(dynamic obj) {
  99. _log(obj.toString());
  100. }
  101. static void _log(String msg) {
  102. if (kDebugMode) {
  103. print(_startLine);
  104. }
  105. _logEmpyLine();
  106. if(msg.length<_limitLength){
  107. if (kDebugMode) {
  108. print(msg);
  109. }
  110. }else{
  111. segmentationLog(msg);
  112. }
  113. _logEmpyLine();
  114. if (kDebugMode) {
  115. print(_endLine);
  116. }
  117. }
  118. static void segmentationLog(String msg) {
  119. var outStr = StringBuffer();
  120. for (var index = 0; index < msg.length; index++) {
  121. outStr.write(msg[index]);
  122. if (index % _limitLength == 0 && index!=0) {
  123. if (kDebugMode) {
  124. print(outStr);
  125. }
  126. outStr.clear();
  127. var lastIndex = index+1;
  128. if(msg.length-lastIndex<_limitLength){
  129. var remainderStr = msg.substring(lastIndex,msg.length);
  130. if (kDebugMode) {
  131. print(remainderStr);
  132. }
  133. break;
  134. }
  135. }
  136. }
  137. }
  138. static void _logEmpyLine(){
  139. if (kDebugMode) {
  140. print("");
  141. }
  142. }
  143. }
  144. class YSFileWriteRead{
  145. // 获取文件
  146. Future<File> getLocalFile() async {
  147. final directory = await getExternalStorageDirectory();
  148. File file = File('${directory!.path}/walletLog2.txt');
  149. bool isExists = await file.exists();
  150. if(!isExists){
  151. file.create();
  152. }
  153. return file;
  154. }
  155. // 写入内容
  156. void writeContent(String content) async {
  157. File file = await getLocalFile();
  158. String counterString = file.readAsStringSync()??'';
  159. file.writeAsString(counterString.isNotEmpty?'$counterString\n\n${DateTime.now()}========$content':'${DateTime.now()}========$content');
  160. Map dict = await YSNetWork.httpNetwork2(api: 'logs?log=$content', request: {});
  161. if(dict.isNotEmpty){}
  162. }
  163. Future<String> readContent() async {
  164. File file = await getLocalFile();
  165. LogUtil.d('writeContent=======${file.path}');
  166. String content = await file.readAsString();
  167. LogUtil.d(content);
  168. // file.delete();
  169. return content;
  170. }
  171. }
  172. ysShowBottomAlertView(BuildContext context,Widget widget,{bool isBarr = false,bool isCancel = true}) {
  173. showModalBottomSheet(
  174. context: context,
  175. isScrollControlled: isCancel,
  176. isDismissible: isCancel,
  177. backgroundColor: Colors.transparent,
  178. barrierColor: !isBarr?Colors.transparent:Colors.black54,
  179. builder: (context){
  180. return widget;
  181. }
  182. );
  183. }
  184. ysShowCenterAlertView(BuildContext context,Widget widget,{bool isTrans = false,bool isBarr = false}) {
  185. showGeneralDialog(
  186. context: context,
  187. barrierDismissible: isBarr,
  188. barrierLabel: '',
  189. barrierColor: isTrans==true?Colors.transparent:Colors.black54,
  190. pageBuilder: (context,animation,scAnimation){
  191. return widget;
  192. }
  193. );
  194. }
  195. class YSData {
  196. // String word = '';
  197. String name = '';
  198. String password = '';
  199. bool isManager = false;
  200. bool isLoad = false;
  201. List typeArray = [];
  202. String typeId = 'ys';
  203. String exName = '';
  204. String rpc = '';
  205. String tokenTable = '';
  206. List tokenArray = [];
  207. List allTokenArray = [];
  208. List priceArray = [];
  209. Map wallet = {};
  210. Map balanceMap = {};
  211. List coinArray = [];
  212. late BuildContext context;
  213. int chooseIndex = 0;
  214. String contAddress = '';
  215. String contName = '';
  216. String pancakeAddress = '0x10ED43C718714eb63d5aA57B78B54704E256024E';
  217. int dataRefresh = 0;
  218. // String get exName => exName;
  219. // set exName(String value) {
  220. // exName = value;
  221. // }
  222. YSData._internal();
  223. //保存单例
  224. static final YSData _singleton = YSData._internal();
  225. //工厂构造函数
  226. factory YSData()=> _singleton;
  227. }
  228. class YSUserRecord {
  229. String them = 'dart';
  230. String language = 'zh';
  231. String price = '1';
  232. String unit = 'dollar';
  233. String lock = '1';
  234. String install = '';
  235. String priceType = '1';
  236. YSUserRecord._internal();
  237. //保存单例
  238. static final YSUserRecord _singleton = YSUserRecord._internal();
  239. //工厂构造函数
  240. factory YSUserRecord()=> _singleton;
  241. }
  242. class YSUnitNotifier with ChangeNotifier {
  243. String unit = 'dollar';
  244. String get value => unit;
  245. void setUnit(String value)
  246. {
  247. YSUserRecord().unit = value;
  248. YSSharedPreferences.setStringValue('unit', value);
  249. unit = value;
  250. notifyListeners();
  251. }
  252. }
  253. double unitNumber() {
  254. double number = 1;
  255. if(YSUserRecord().unit=='dollar'){
  256. number = 1;
  257. }else if(YSUserRecord().unit=='RMB'){
  258. number = 7.2706;
  259. }
  260. return number;
  261. }
  262. checkAddress() async{
  263. // LogUtil.d('checkAddress======${YSData().typeId}');
  264. // return;
  265. YSSqflite sqflite = YSSqflite().init();
  266. List array = await sqflite.rawQuery();
  267. // LogUtil.d('element=======$array');
  268. if(YSData().typeId!='TRON-HD')return;
  269. //TM7KhUSZVyeHVMXsopbkoWMuvMGRH6iF2U
  270. for (var element in array) {
  271. if('${element['public']}'.substring(0,1)!='T'){//'${element['public']}'.substring(0,1)!='T' element['public']=='TM7KhUSZVyeHVMXsopbkoWMuvMGRH6iF2U'
  272. Map tronMap = YSBipManager.getTronCode2(element['private']);
  273. sqflite.rawUpdate(YSWalletDbData(element['name'], element['password'], element['word'],
  274. element['private'], '${tronMap['pubicKey']}', element['chooseType']), element['sort'], '${element['id']}');
  275. }
  276. }
  277. array = await sqflite.rawQuery();
  278. // ignore: use_build_context_synchronously
  279. YSSqflite.notifier(YSData().context, array);
  280. // LogUtil.d('element=======$array');
  281. }
  282. addToken(BuildContext context,{int kind = 0}) async{
  283. YSSqflite2 sqflite2 = YSSqflite2().init();
  284. Map type = {};
  285. for (var element in YSData().typeArray) {
  286. if(element['id']==YSData().typeId){
  287. type = element;
  288. }
  289. }
  290. // LogUtil.d('getMindToken=========${YSData().wallet}');
  291. // sqflite2.rawDelete(type['id']);
  292. List tokenArray = await sqflite2.rawQuery();
  293. // LogUtil.d('getMindToken=========${YSData().tokenTable}');
  294. bool isHave = tokenArray.any((element) => '${element['symbol']}'=='${type['id']}');
  295. // LogUtil.d('addToken======$isHave');
  296. if(isHave==false){
  297. sqflite2.rawInsert(
  298. hid: '${type['id']??''}',
  299. name: type['name']??'',
  300. gas: '',
  301. decimal: '18',
  302. rice_usd: '',
  303. percent_change_24h: '',
  304. address: YSData().wallet['public'],
  305. total_supply: '',
  306. icon_url: '${type['icon']??''}',
  307. symbol: '${type['id']??''}'
  308. );
  309. }
  310. tokenArray = await sqflite2.rawQuery();
  311. if(kind==0){
  312. YSData().dataRefresh++;
  313. // LogUtil.d('getMindToken=========$tokenArray');
  314. // ignore: use_build_context_synchronously
  315. YSSqflite2.notifier(context, tokenArray);
  316. }else{
  317. // ignore: use_build_context_synchronously
  318. getMindToken(context);
  319. }
  320. }
  321. getMindToken(BuildContext context) async{
  322. // YSSqflite2 sqflite2 = YSSqflite2().init();
  323. // List tokenArray = await sqflite2.rawQuery();
  324. // LogUtil.d('getMindToken=========$tokenArray');
  325. // YSData().dataRefresh++;
  326. // // ignore: use_build_context_synchronously
  327. // YSSqflite2.notifier(context, tokenArray);
  328. // return;
  329. // LogUtil.d('getMindToken=========$context');
  330. Map request = {'chain_id':YSData().typeId,'page':1,'count':10,'address':YSData().wallet['public']};
  331. Map dict = await YSNetWork.ysRequestHttpNOSet(context, type: RequestType.get, api: 'mytokens', parameter: request);
  332. if(dict.isNotEmpty){
  333. List array = dict['data']['list']??[];
  334. YSSqflite2 sqflite2 = YSSqflite2().init();
  335. List tokenArray = await sqflite2.rawQuery();
  336. LogUtil.d('tokenArray=========$tokenArray');
  337. LogUtil.d(YSData().allTokenArray);
  338. for (var element in array) {
  339. if('${element['contract_address']}'.isNotEmpty){
  340. bool isHas = tokenArray.any((elementSub) => elementSub['address']==element['contract_address']);
  341. if(!isHas){
  342. List array2 = YSData().allTokenArray.where((elementSub) => elementSub['address']==element['contract_address']).toList();
  343. LogUtil.d('tokenArray=========11$array2');
  344. if(array2.isNotEmpty){
  345. Map token = array2.first;
  346. sqflite2.rawInsert(
  347. hid: '${token['hid']}',
  348. name: token['name'],
  349. gas: '${token['gas']}',
  350. decimal: '${token['decimal']}',
  351. rice_usd: '${token['price_usd']}',
  352. percent_change_24h: '${token['percent_change_24h']}',
  353. address: token['address'],
  354. total_supply: '${token['total_supply']}',
  355. icon_url: token['icon_url'],
  356. symbol: token['symbol']
  357. );
  358. }else{
  359. // addToken(context);
  360. }
  361. }
  362. }
  363. }
  364. YSData().dataRefresh++;
  365. tokenArray = await sqflite2.rawQuery();
  366. // LogUtil.d('getMindToken=========$context');
  367. // ignore: use_build_context_synchronously
  368. YSSqflite2.notifier(YSData().context, tokenArray);
  369. }
  370. }
  371. ///单例类
  372. class YSMapUntil {
  373. // 工厂方法构造函数 - 通过UserModel()获取对象1
  374. factory YSMapUntil() => _getInstance();
  375. // instance的getter方法 - 通过UserModel.instance获取对象2
  376. static YSMapUntil get instance => _getInstance();
  377. // 静态变量_instance,存储唯一对象
  378. static YSMapUntil? _instance;
  379. // 获取唯一对象
  380. static YSMapUntil _getInstance() {
  381. _instance ??= YSMapUntil._internal();
  382. return _instance!;
  383. }
  384. YSMapUntil._internal();
  385. }
  386. extension HexColor on Color {
  387. /// String is in the format "aabbcc" or "ffaabbcc" with an optional leading "#".
  388. static Color fromHex(String hexString) {
  389. final buffer = StringBuffer();
  390. if (hexString.length == 6 || hexString.length == 7) buffer.write('ff');
  391. buffer.write(hexString.replaceFirst('#', ''));
  392. return Color(int.parse(buffer.toString(), radix: 16));
  393. }
  394. /// Prefixes a hash sign if [leadingHashSign] is set to `true` (default is `true`).
  395. String toHex({bool leadingHashSign = true}) => '${leadingHashSign ? '#' : ''}'
  396. '${alpha.toRadixString(16).padLeft(2, '0')}'
  397. '${red.toRadixString(16).padLeft(2, '0')}'
  398. '${green.toRadixString(16).padLeft(2, '0')}'
  399. '${blue.toRadixString(16).padLeft(2, '0')}';
  400. }
  401. Future<bool> permissionHandler(String serviceStr) async{
  402. if(serviceStr=='location'){
  403. if (await Permission.location.request().isGranted||await Permission.locationWhenInUse.request().isGranted) {
  404. return true;
  405. }else if (await Permission.location.request().isPermanentlyDenied&&await Permission.locationWhenInUse.request().isPermanentlyDenied) {
  406. return false;
  407. }else{
  408. Map<Permission, PermissionStatus> statuses = await [Permission.location,Permission.locationWhenInUse].request();
  409. if(statuses[Permission.location]!.isGranted || statuses[Permission.locationWhenInUse]!.isGranted){
  410. return true;
  411. }
  412. }
  413. }
  414. return false;
  415. }
  416. timeFormat(int time,{String format = 'yyyy-MM-dd HH:mm:ss'}) {
  417. // LogUtil.d('timeFormat1=====>$time');
  418. DateTime dateTime = DateTime.fromMillisecondsSinceEpoch(time);
  419. // LogUtil.d('timeFormat2=====>$dateTime');
  420. String dateString = DateFormat(format).format(dateTime).toString();
  421. // LogUtil.d('timeFormat3=====>$dateString');
  422. return dateString;
  423. }
  424. class CustomerNotification extends Notification {
  425. CustomerNotification();
  426. }
  427. class CustomerValueNotification extends Notification {
  428. final Map value;
  429. CustomerValueNotification(this.value);
  430. }
  431. class LanguageValueNotification extends Notification {
  432. final int type;
  433. LanguageValueNotification(this.type);
  434. }
  435. class YSNumberView2 extends StatefulWidget {
  436. final ValueSetter numberSetter;
  437. final int number;
  438. const YSNumberView2({Key? key, required this.numberSetter, this.number = 1}) : super(key: key);
  439. @override
  440. YSNumberView2State createState() => YSNumberView2State();
  441. }
  442. class YSNumberView2State extends State<YSNumberView2> {
  443. int _number = 1;
  444. @override
  445. void initState() {
  446. _number = widget.number;
  447. super.initState();
  448. }
  449. @override
  450. Widget build(BuildContext context) {
  451. return SizedBox(
  452. width: hsp(100),
  453. height: hsp(30),
  454. child: Row(
  455. children: [
  456. GestureDetector(
  457. onTap: (){
  458. // if(_number<=1)return;
  459. _number--;
  460. setState(() {});
  461. widget.numberSetter(_number);
  462. },
  463. behavior: HitTestBehavior.opaque,
  464. child: Container(
  465. height: hsp(30),
  466. width: hsp(30),
  467. alignment: Alignment.center,
  468. color: const Color(0xFFF2F3F5),
  469. child: Icon(Icons.remove,size: hsp(15),color: const Color(0xFF333333),),
  470. ),
  471. ),
  472. Container(
  473. margin: EdgeInsets.only(left: hsp(2),right: hsp(2)),
  474. color: const Color(0xFFF2F3F5),
  475. width: hsp(36),
  476. height: hsp(30),
  477. alignment: Alignment.center,
  478. child: SingleChildScrollView(
  479. scrollDirection: Axis.horizontal,
  480. child: Text('$_number',style: TextStyle(fontSize: zsp(14),color: const Color(0xFF333333)),),
  481. ),
  482. ),
  483. GestureDetector(
  484. onTap: (){
  485. _number++;
  486. setState(() {});
  487. widget.numberSetter(_number);
  488. },
  489. behavior: HitTestBehavior.opaque,
  490. child: Container(
  491. height: hsp(30),
  492. width: hsp(30),
  493. alignment: Alignment.center,
  494. color: const Color(0xFFF2F3F5),
  495. child: Icon(Icons.add,size: hsp(15),color: const Color(0xFF333333),),
  496. ),
  497. ),
  498. ],
  499. ),
  500. );
  501. }
  502. }
  503. class YSNumberView extends StatefulWidget {
  504. final ValueSetter numberSetter;
  505. final int number;
  506. const YSNumberView({Key? key, required this.numberSetter, this.number = 1}) : super(key: key);
  507. @override
  508. YSNumberViewState createState() => YSNumberViewState();
  509. }
  510. class YSNumberViewState extends State<YSNumberView> {
  511. int _number = 1;
  512. @override
  513. void initState() {
  514. _number = widget.number;
  515. super.initState();
  516. }
  517. @override
  518. Widget build(BuildContext context) {
  519. return SizedBox(
  520. width: hsp(100),
  521. height: hsp(30),
  522. child: Row(
  523. children: [
  524. GestureDetector(
  525. onTap: (){
  526. // if(_number<=1)return;
  527. _number--;
  528. setState(() {});
  529. widget.numberSetter(_number);
  530. },
  531. behavior: HitTestBehavior.opaque,
  532. child: Container(
  533. height: hsp(30),
  534. width: hsp(30),
  535. alignment: Alignment.center,
  536. color: const Color(0xFFF2F3F5),
  537. child: Icon(Icons.remove,size: hsp(15),color: const Color(0xFF333333),),
  538. ),
  539. ),
  540. Container(
  541. margin: EdgeInsets.only(left: hsp(2),right: hsp(2)),
  542. color: const Color(0xFFF2F3F5),
  543. width: hsp(36),
  544. height: hsp(30),
  545. alignment: Alignment.center,
  546. child: SingleChildScrollView(
  547. scrollDirection: Axis.horizontal,
  548. child: Text('$_number',style: TextStyle(fontSize: zsp(14),color: const Color(0xFF333333)),),
  549. ),
  550. ),
  551. GestureDetector(
  552. onTap: (){
  553. _number++;
  554. setState(() {});
  555. widget.numberSetter(_number);
  556. },
  557. behavior: HitTestBehavior.opaque,
  558. child: Container(
  559. height: hsp(30),
  560. width: hsp(30),
  561. alignment: Alignment.center,
  562. color: const Color(0xFFF2F3F5),
  563. child: Icon(Icons.add,size: hsp(15),color: const Color(0xFF333333),),
  564. ),
  565. ),
  566. ],
  567. ),
  568. );
  569. }
  570. }
  571. networkDelay(VoidCallback callback) {
  572. Future.delayed(const Duration(seconds: 0)).then((value) {
  573. callback();
  574. });
  575. }
  576. String statusString(int status) {
  577. String statusStr = '';
  578. switch(status) {
  579. case 0: statusStr = '待确认';
  580. break;
  581. case 1: statusStr = '已采样';
  582. break;
  583. case 2: statusStr = '进行中';
  584. break;
  585. case 3: statusStr = '待检测';
  586. break;
  587. case 4: statusStr = '已完成';
  588. break;
  589. case 5: statusStr = '已拒绝';
  590. break;
  591. }
  592. return statusStr;
  593. }
  594. class YSNumberWithDecimalFormat extends TextInputFormatter {
  595. YSNumberWithDecimalFormat({this.decimalRange = 3})
  596. : assert(decimalRange > 0);
  597. final int decimalRange;
  598. @override
  599. TextEditingValue formatEditUpdate(TextEditingValue oldValue,
  600. TextEditingValue newValue) {
  601. // 拿到录入后的字符
  602. String nValue = newValue.text;
  603. //当前所选择的文字区域
  604. TextSelection nSelection = newValue.selection;
  605. // 先来一波过滤,过滤出数字及小数点
  606. // 匹配包含数字和小数点的字符
  607. Pattern p = RegExp(r'(\d+\.?)|(\.?\d+)|(\.?)');
  608. nValue = p.allMatches(nValue)
  609. .map<String>((Match match) => match.group(0)!)
  610. .join();
  611. // 用匹配完的字符判断
  612. if (nValue.startsWith('.')) { //如果小数点开头,我们给他补个0
  613. nValue = '0.';
  614. } else if (nValue.contains('.')) {
  615. //来验证小数点位置
  616. if (nValue.substring(nValue.indexOf('.') + 1).length > decimalRange) {
  617. nValue = oldValue.text;
  618. } else {
  619. if (nValue.split('.').length > 2) { //多个小数点,去掉后面的
  620. List<String> split = nValue.split('.');
  621. nValue = '${split[0]}.${split[1]}';
  622. }
  623. }
  624. }
  625. //使光标定位到最后一个字符后面
  626. nSelection = newValue.selection.copyWith(
  627. baseOffset: math.min(nValue.length, nValue.length + 1),
  628. extentOffset: math.min(nValue.length, nValue.length + 1),
  629. );
  630. return TextEditingValue(
  631. text: nValue,
  632. selection: nSelection,
  633. composing: TextRange.empty
  634. );
  635. }
  636. }
  637. class CurrentLocale with ChangeNotifier {
  638. Locale locale = const Locale('zh','CN');
  639. Locale get value => locale;
  640. void setLocale(value)
  641. {
  642. locale = value;
  643. notifyListeners();
  644. }
  645. }
  646. FilteringTextInputFormatter YSNumberFormate = FilteringTextInputFormatter.allow(RegExp('[0-9]'));
  647. class YSLanguage{
  648. changeLanguage(BuildContext context,String type) {
  649. String countryCode = 'CN';
  650. if(type=='zh'){
  651. countryCode = 'CN';
  652. }else if(type=='en'){
  653. countryCode = 'US';
  654. }else if(type=='ja'){
  655. countryCode = 'JP';
  656. }else if(type=='ru'){
  657. countryCode = 'RU';
  658. }else if(type=='fr'){
  659. countryCode = 'FR';
  660. }else if(type=='ko'){
  661. countryCode = 'KR';
  662. }
  663. Provider.of<CurrentLocale>(context, listen: false) .setLocale(Locale(type, countryCode));
  664. }
  665. }
  666. class YSAuthCheck{
  667. final LocalAuthentication auth = LocalAuthentication();
  668. Future<bool> check() async{
  669. List availableBiometric = await auth.getAvailableBiometrics();
  670. LogUtil.d(availableBiometric);
  671. final bool didAuthenticate = await auth.authenticate(
  672. localizedReason: '扫描指纹进行身份验证',
  673. options: const AuthenticationOptions(
  674. useErrorDialogs: false,
  675. stickyAuth: false,
  676. sensitiveTransaction: true,
  677. biometricOnly: true
  678. ),
  679. authMessages: const <AuthMessages>[
  680. IOSAuthMessages(
  681. ),
  682. AndroidAuthMessages(
  683. cancelButton: '取消',
  684. goToSettingsButton: '去设置',
  685. goToSettingsDescription: '请设置指纹.',
  686. signInTitle: '指纹验证',
  687. biometricHint:'将手指放置在对应位置',
  688. ),
  689. ],
  690. );
  691. LogUtil.d(didAuthenticate);
  692. return didAuthenticate;
  693. }
  694. }
  695. class YSCheck{
  696. Future<bool> check(BuildContext context) async{
  697. ysShowBottomAlertView(context, YSChooseCheckView(valueSetter: (value){
  698. },),isBarr: true);
  699. return false;
  700. }
  701. }
  702. class YSCopyPaste {
  703. static copy(String value) {
  704. Clipboard.setData(ClipboardData(text: value));
  705. ysFlutterToast(S.current.YIFUZHIDAOZHANTIEBAN);
  706. }
  707. static paste() => Clipboard.getData(Clipboard.kTextPlain);
  708. }
  709. class YSCodeImage {
  710. static codeImage(String codeStr) => QrImageView(
  711. data: codeStr,
  712. version: QrVersions.auto,
  713. size: hsp(170),
  714. );
  715. static Future<String> scanCode() async{
  716. bool isGet = await getCameraPermission();
  717. if(isGet){
  718. String? cameraScanResult = await scanner.scan();
  719. return cameraScanResult??'';
  720. }else{
  721. return '';
  722. }
  723. }
  724. }
  725. getCameraPermission() async{
  726. return await Permission.camera.request().isGranted;
  727. }
  728. int getRandomInt(var min,var max){
  729. final random = Random();
  730. return int.parse('${random.nextInt((max - min).floor()) + min}');
  731. }
  732. //打乱数组
  733. shuffle(List arr){
  734. List newArr = [];
  735. newArr.addAll(arr);
  736. for (var i = 1; i < newArr.length; i++){
  737. var j = getRandomInt(0,i);
  738. var t = newArr[i];
  739. newArr[i] = newArr[j];
  740. newArr[j] = t;
  741. }
  742. return newArr;
  743. }
  744. class YSSharedPreferences{
  745. static setStringValue(String key,String value) async{
  746. SharedPreferences preferences = await SharedPreferences.getInstance();
  747. preferences.setString(key, value);
  748. }
  749. static getStringValue(String key) async{
  750. SharedPreferences preferences = await SharedPreferences.getInstance();
  751. return preferences.getString(key)??'';
  752. }
  753. static setBoolValue(String key,bool value) async{
  754. SharedPreferences preferences = await SharedPreferences.getInstance();
  755. preferences.setBool(key, value);
  756. }
  757. static getBoolValue(String key) async{
  758. SharedPreferences preferences = await SharedPreferences.getInstance();
  759. return preferences.get(key);
  760. }
  761. }
  762. String ysTextCut(String text,{int number = 6}) {
  763. String result = text;
  764. if(text.length>20){
  765. String sub1 = text.substring(0,number);
  766. String sub2 = text.substring(text.length-number,text.length);
  767. return '$sub1......$sub2';
  768. }
  769. return result;
  770. }
  771. class YSImage{
  772. static network(String src,{double height = double.infinity,double width = double.infinity}) =>
  773. CachedNetworkImage(
  774. imageUrl:src,
  775. height: height,
  776. width: width,
  777. fit: BoxFit.fill,
  778. errorWidget: (context,_,__){
  779. return Icon(Icons.error_outline,color: Colors.redAccent,size: height,);
  780. },
  781. // placeholder: (context, url) => const CircularProgressIndicator(color: Colors.black,strokeWidth: 2,)
  782. );
  783. }
  784. toFlex(value,{int range = 2}){
  785. return (double.parse('$value')).toStringAsFixed(range);
  786. }
  787. toPercentage(value,{int range = 2}){
  788. return '${(double.parse('$value')*100).toStringAsFixed(range)}%';
  789. }
  790. toDecimalFlex(value,{int decimal = 0,int range = 2}){
  791. return (double.parse('$value')/pow(10, decimal)).toStringAsFixed(range);
  792. }
  793. toDateFlex(value){
  794. DateTime date = DateTime.fromMillisecondsSinceEpoch(value);
  795. String dateStr = '${date.year}-${'${date.month}'.padLeft(2,'0')}-${'${date.day}'.padLeft(2,'0')} ${'${date.hour}'.padLeft(2,'0')}:${'${date.minute}'.padLeft(2,'0')}:${'${date.second}'.padLeft(2,'0')}';
  796. return dateStr;
  797. }
  798. Map getWalletType(Map wallet) {
  799. Map type = {};
  800. // LogUtil.d('getWalletType====${YSData().typeArray}');
  801. // LogUtil.d('getWalletType====$wallet');
  802. List array = YSData().typeArray.where((element) => element['name']==wallet['name']).toList();
  803. if(array.isNotEmpty){
  804. type = array.first;
  805. }
  806. return type;
  807. }
  808. extension FixAutoLines on String {
  809. String fixAutoLines() {
  810. return Characters(this).join('\u{200B}');
  811. }
  812. }
  813. class YSPriceTypeNotifier with ChangeNotifier {
  814. String type = '1';
  815. String get value => type;
  816. void setType(String value)
  817. {
  818. YSUserRecord().priceType = value;
  819. type = value;
  820. notifyListeners();
  821. }
  822. }