utils.dart 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import 'dart:math' as math;
  2. import 'package:flutter/services.dart';
  3. String bytesToSize(int bytes) {
  4. if (bytes == 0) return '0 B';
  5. const k = 1024;
  6. const sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
  7. final i = (math.log(bytes) / math.log(k)).floor();
  8. return '${(bytes / math.pow(k, i)).toStringAsFixed(2)} ${sizes[i]}';
  9. }
  10. const Map<String, Map<String, String>> _copyCommandLineProxyTypes = {
  11. 'cmd': {'prefix': 'set ', 'quot': '', 'join': '&&'},
  12. 'bash': {'prefix': 'export ', 'quot': '"', 'join': ' && '},
  13. 'powershell': {'prefix': '\$env:', 'quot': '"', 'join': ';'},
  14. };
  15. Future<void> copyCommandLineProxy(String type, {String? http, String? https}) async {
  16. final types = _copyCommandLineProxyTypes[type];
  17. if (types == null) return;
  18. final prefix = types['prefix']!;
  19. final quot = types['quot']!;
  20. final join = types['join']!;
  21. List<String> commands = [];
  22. if (http != null) commands.add('${prefix}http_proxy=${quot}http://$http$quot');
  23. if (https != null) commands.add('${prefix}https_proxy=${quot}http://$https$quot');
  24. if (commands.isNotEmpty) await Clipboard.setData(ClipboardData(text: commands.join(join)));
  25. }
  26. extension OrNull<T> on T {
  27. T? orNull(bool a) {
  28. return a ? this : null;
  29. }
  30. }
  31. extension BindOne<T, R> on R Function(T a) {
  32. R Function() bindOne(T a) {
  33. return () => this(a);
  34. }
  35. }
  36. extension BindFirst<T, T2, R> on R Function(T a, T2 b) {
  37. R Function(T2 b) bindFirst(T a) {
  38. return (T2 b) => this(a, b);
  39. }
  40. }
  41. extension MapIndex<T> on List<T> {
  42. List<R> mapIndex<R>(R Function(int index, T item) fn) {
  43. final List<R> list = [];
  44. for (int idx = 0; idx < length; idx++) {
  45. list.add(fn(idx, this[idx]));
  46. }
  47. return list;
  48. }
  49. }
  50. enum RunningState {
  51. starting,
  52. running,
  53. stopping,
  54. stoped,
  55. error,
  56. }