Dart(Flutter)识别CPU架构

夏沫花火zzz🌙 (Muska_Ami) Lv4

思路

平台兼容性

  • Windows 平台有一个叫做 PROCESSOR_ARCHITECTURE 的环境变量,里面有 CPU 架构,比如我的为 AMD64
  • Unix 系则可以通过 uname -m 命令来获取 CPU 架构

实现

Windows

通过 dart:io 库来获取系统环境变量

1
Platform.environment['PROCESSOR_ARCHITECTURE'];

Unix系

通过 dart:io 库运行命令并读取返回值获取

1
2
var info = await Process.run('uname', ['-m']);
info.stdout.toString().replaceAll('\n', '');

完整实现

源码参考自此 Gist : https://gist.github.com/corbindavenport/d04085e2ac42da303efbaccaa717f223

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import 'dart:io';

/// Copy & modify from GitHub Gists
/// https://gist.github.com/corbindavenport/d04085e2ac42da303efbaccaa717f223
class CPUArch {

// Function get current CPU architecture
static Future<String> getCPUArchitecture() async {
var cpu;
if (Platform.isWindows) {
cpu = Platform.environment['PROCESSOR_ARCHITECTURE'];
// var cpu = envVars['PROCESSOR_ARCHITECTURE'];
} else {
var info = await Process.run('uname', ['-m']);
cpu = info.stdout.toString().replaceAll('\n', '');
}
switch (cpu) {
case 'x86_64' || 'X86_64' || 'x64' || 'X64' || 'AMD64':
cpu = 'amd64';
break;
case 'x86' || 'X86' || 'i386' || 'I386' || 'x32' || 'X32' || '386' || 'AMD32':
cpu = 'amd32';
break;
}
return cpu;
}

}

用例:

1
2
/// By giving a demo
CPUArch.getCPUArchitecture();
  • 标题: Dart(Flutter)识别CPU架构
  • 作者: 夏沫花火zzz🌙 (Muska_Ami)
  • 创建于 : 2023-12-30 12:13:18
  • 更新于 : 2024-10-03 16:39:27
  • 链接: https://blog.1l1.icu/2023/12/30/dart-flutter-shi-bie-cpu-jia-gou/
  • 版权声明: 本文章采用 CC BY-SA 4.0 进行许可。
 评论
此页目录
Dart(Flutter)识别CPU架构