memory_monitor.dart 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. import 'dart:async';
  2. import 'package:flutter/material.dart';
  3. import 'package:flyinsono/lab/color/lab_colors.dart';
  4. import 'package:universal_html/js.dart' as js;
  5. class MemoryMonitor extends StatefulWidget {
  6. const MemoryMonitor({super.key});
  7. @override
  8. State<MemoryMonitor> createState() => _MemoryMonitorState();
  9. }
  10. class _MemoryMonitorState extends State<MemoryMonitor> {
  11. String totalMemory = '';
  12. String allocatedMemory = '';
  13. String availableMemory = '';
  14. Timer? _timer;
  15. @override
  16. Widget build(BuildContext context) {
  17. if (totalMemory.isEmpty) {
  18. return Container();
  19. }
  20. return Row(
  21. mainAxisAlignment: MainAxisAlignment.end,
  22. children: <Widget>[
  23. Flexible(
  24. child: Text(
  25. '已用内存:$totalMemory MB',
  26. overflow: TextOverflow.ellipsis,
  27. style: TextStyle(color: LabColors.text300),
  28. ),
  29. ),
  30. Flexible(child: SizedBox(width: 10)),
  31. Flexible(
  32. child: Text(
  33. '可用内存:$availableMemory MB',
  34. overflow: TextOverflow.ellipsis,
  35. style: TextStyle(color: LabColors.text300),
  36. ),
  37. ),
  38. ],
  39. );
  40. }
  41. @override
  42. void initState() {
  43. super.initState();
  44. _timer = Timer.periodic(
  45. const Duration(seconds: 3),
  46. (Timer timer) {
  47. updateMemoryInfo();
  48. },
  49. );
  50. }
  51. @override
  52. void dispose() {
  53. super.dispose();
  54. _timer?.cancel();
  55. _timer = null;
  56. }
  57. void updateMemoryInfo() {
  58. try {
  59. // 更新内存数据
  60. js.context.callMethod("getMemoryUsageInfo", [
  61. (
  62. dynamic success,
  63. dynamic totalMemory,
  64. dynamic allocatedMemory,
  65. dynamic availableMemory,
  66. ) {
  67. if (success is bool && success) {
  68. if (totalMemory is num &&
  69. allocatedMemory is num &&
  70. availableMemory is num) {
  71. final String _totalMemory =
  72. (totalMemory.toInt() / 1048576).toStringAsFixed(2);
  73. final String _allocatedMemory =
  74. (allocatedMemory.toInt() / 1048576).toStringAsFixed(2);
  75. final String _availableMemory =
  76. (availableMemory.toInt() / 1048576).toStringAsFixed(2);
  77. setState(() {
  78. this.totalMemory = _totalMemory;
  79. this.allocatedMemory = _allocatedMemory;
  80. this.availableMemory = _availableMemory;
  81. });
  82. } else {
  83. print('内存数据类型错误');
  84. }
  85. } else {
  86. print('获取内存数据失败');
  87. }
  88. }
  89. ]);
  90. } catch (e) {
  91. print('获取内存数据失败');
  92. }
  93. }
  94. }