import 'package:flutter/material.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:get/get.dart'; import 'dart:math'; class Utils { static Utils? _instance; Utils._internal(); static Utils getInstance() { _instance ??= Utils._internal(); return _instance!; } /// 关闭键盘 static void hideKeyboard() { FocusScopeNode? currentFocus = Get.focusScope?.nearestScope; if (currentFocus == null) { return; } if (!currentFocus.hasPrimaryFocus && currentFocus.focusedChild != null) { FocusManager.instance.primaryFocus?.unfocus(); } } void setTimeOut(int seconds, call) => Future.delayed(Duration(seconds: seconds), call); Future setTimeOutMilliseconds(int milliseconds, call) => Future.delayed(Duration(milliseconds: milliseconds), call); // 是否是平板 static bool isPad([double mobilePhoneScale = 1.2]) { return ScreenUtil().scaleWidth > mobilePhoneScale; } static String getDoubleRemoveZero(double? val, [String? defaultVal]) { try { if (val == null) throw Exception('数据为空'); List _valArr = val.toString().split('.'); if (_valArr.length >= 2) { if (int.parse(_valArr[1]) == 0) { return val.toInt().toString(); } return val.toString(); } return val.toInt().toString(); } catch (e) { return defaultVal ?? ''; } } /// 去除小数点 static String doubleToStringAsFixed(double val, {int fractionDigits = 2}) { return val.toStringAsFixed(fractionDigits).replaceAll(RegExp(r'\.0*$'), ''); } static calcRate(int divisor, int dividend) { if (dividend != 0) { return ((100 * divisor) / dividend); // return ((100 * divisor) / dividend).toStringAsFixed(0); } else { return 0.0; } } /// 秒转时分秒 static String second2HMS(int sec, {bool isEasy = false}) { String hms = "0"; if (!isEasy) hms = "0秒"; if (sec > 0) { int h = sec ~/ 3600; int m = (sec % 3600) ~/ 60; int s = sec % 60; if (h > 0) { hms = "$h时$m分$s秒"; } else { if (m > 0) { hms = "$m分$s秒"; } else { hms = "$s秒"; } } } return hms; } static DateTime getWeekStartDate() { DateTime now = DateTime.now(); int dayOfWeek = now.weekday; // 获取今天是周几(1代表周一,7代表周日) int diff = dayOfWeek - 1; // 计算今天距离周一的天数差 if (diff < 0) { diff += 7; // 如果是周日,则需要加上一周的天数 } return now.subtract(Duration(days: diff)); // 减去天数差,得到本周一的时间 } static DateTime getWeekEndDate() { DateTime now = DateTime.now(); int dayOfWeek = now.weekday; // 获取今天是周几 int diff = 7 - dayOfWeek; // 计算今天距离周日的天数差 if (diff == 0) { diff = 7; // 如果是周日,则加上一周的天数 } return now.add(Duration(days: diff)); // 加上天数差减一,得到本周日的时间 } static String getQuestionSource(int type) { var str = ''; switch (type) { case 1: str = '预习'; break; case 3: str = '复习'; break; case 4: str = '作业'; break; case 5: str = '考试'; break; } return str; } } // 是否是平板 bool isPad([double mobilePhoneScale = 1.2]) { return ScreenUtil().scaleWidth > mobilePhoneScale; } void toUpState(Function(void Function()) setState, VoidCallback fn, bool mounted) { if (mounted) setState(fn); }