You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Flutter中获取硬件信息?求Dart实现主板序列号的代码

Dart 获取主板序列号

Dart本身没有直接访问硬件信息的原生API,需通过调用系统命令或读取系统文件实现,不同操作系统的实现方式不同:

Windows 平台

通过执行wmic baseboard get serialnumber命令获取,代码示例:

import 'dart:io';

Future<String?> getMotherboardSerial() async {
  try {
    final result = await Process.run('wmic', ['baseboard', 'get', 'serialnumber']);
    if (result.exitCode == 0) {
      final lines = result.stdout.toString().trim().split('\n');
      if (lines.length >= 2) {
        final serial = lines[1].trim();
        return serial.isNotEmpty ? serial : null;
      }
    }
  } catch (e) {
    print('获取主板序列号失败:$e');
  }
  return null;
}

void main() async {
  final serial = await getMotherboardSerial();
  print('主板序列号:${serial ?? '无法获取'}');
}

Linux 平台

读取/sys/class/dmi/id/board_serial文件(需root权限),代码示例:

import 'dart:io';

Future<String?> getMotherboardSerial() async {
  try {
    final file = File('/sys/class/dmi/id/board_serial');
    if (await file.exists()) {
      final serial = await file.readAsString();
      return serial.trim().isNotEmpty ? serial.trim() : null;
    }
  } catch (e) {
    print('获取主板序列号失败:$e');
  }
  return null;
}

macOS 平台

执行system_profiler SPHardwareDataType命令并解析输出,代码示例:

import 'dart:io';

Future<String?> getMotherboardSerial() async {
  try {
    final result = await Process.run('system_profiler', ['SPHardwareDataType']);
    if (result.exitCode == 0) {
      final output = result.stdout.toString();
      final regex = RegExp(r'Serial Number \(system\):\s*(.*)');
      final match = regex.firstMatch(output);
      if (match != null) {
        final serial = match.group(1)?.trim();
        return serial?.isNotEmpty ?? false ? serial : null;
      }
    }
  } catch (e) {
    print('获取主板序列号失败:$e');
  }
  return null;
}

Flutter 中获取硬件信息

Flutter作为跨平台框架,需依赖平台特定实现,常用两种方式:

1. 使用第三方插件

社区成熟插件可快速获取硬件信息,推荐:

  • device_info_plus:支持多平台,可获取设备型号、系统版本、唯一标识符等
  • system_info:可获取CPU、内存、磁盘等系统硬件信息

以device_info_plus为例,步骤如下:

安装依赖

在pubspec.yaml中添加:

dependencies:
  device_info_plus: ^9.1.1

使用示例

import 'package:device_info_plus/device_info_plus.dart';
import 'dart:io';

Future<void> getDeviceInfo() async {
  final DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
  
  if (Platform.isAndroid) {
    AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;
    print('Android 设备ID:${androidInfo.id}');
    print('设备型号:${androidInfo.model}');
    print('主板:${androidInfo.board}');
  }
  
  else if (Platform.isIOS) {
    IosDeviceInfo iosInfo = await deviceInfo.iosInfo;
    print('iOS 设备ID:${iosInfo.identifierForVendor}');
    print('设备型号:${iosInfo.model}');
    print('序列号:${iosInfo.serialNumber}');
  }
  
  else if (Platform.isWindows) {
    WindowsDeviceInfo windowsInfo = await deviceInfo.windowsInfo;
    print('Windows 设备ID:${windowsInfo.deviceId}');
    print('主板制造商:${windowsInfo.boardManufacturer}');
    print('主板型号:${windowsInfo.boardProduct}');
  }
}

2. 自定义平台通道(Method Channel)

若插件无法满足需求,可通过Method Channel调用原生代码实现:

Flutter 端代码

import 'package:flutter/services.dart';

class HardwareInfo {
  static const MethodChannel _channel = MethodChannel('hardware_info');

  static Future<String?> getMotherboardSerial() async {
    try {
      final String? serial = await _channel.invokeMethod('getMotherboardSerial');
      return serial;
    } on PlatformException catch (e) {
      print('获取失败:${e.message}');
      return null;
    }
  }
}

Android 端原生代码(Kotlin)

在MainActivity.kt中添加:

class MainActivity : FlutterActivity() {
    private val CHANNEL = "hardware_info"

    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
        MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler { call, result ->
            if (call.method == "getMotherboardSerial") {
                val serial = getMotherboardSerial()
                result.success(serial ?: "无法获取")
            } else {
                result.notImplemented()
            }
        }
    }

    private fun getMotherboardSerial(): String? {
        return try {
            Class.forName("android.os.SystemProperties")
                .getMethod("get", String::class.java)
                .invoke(null, "ro.serialno") as String
        } catch (e: Exception) {
            null
        }
    }
}

iOS 端原生代码(Swift)

在AppDelegate.swift中添加:

import Flutter
import UIKit

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    let controller : FlutterViewController = window?.rootViewController as! FlutterViewController
    let hardwareChannel = FlutterMethodChannel(name: "hardware_info",
                                              binaryMessenger: controller.binaryMessenger)
    hardwareChannel.setMethodCallHandler({
      [weak self] (call: FlutterMethodCall, result: FlutterResult) -> Void in
      guard call.method == "getMotherboardSerial" else {
        result(FlutterMethodNotImplemented)
        return
      }
      result(self?.getMotherboardSerial())
    })
    GeneratedPluginRegistrant.register(with: self)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
    
  private func getMotherboardSerial() -> String? {
    var serial: String?
    let platformExpert = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching("IOPlatformExpertDevice"))
    if platformExpert != 0 {
      serial = IORegistryEntryCreateCFProperty(platformExpert, kIOPlatformSerialNumberKey as CFString, kCFAllocatorDefault, 0).takeRetainedValue() as? String
      IOObjectRelease(platformExpert)
    }
    return serial
  }
}

内容的提问来源于stack exchange,提问作者atishn90

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 05:36:00