在 Flutter 中使用 device_info_plus 插件获取设备信息,步骤如下:
1. 添加依赖
在 pubspec.yaml 文件的 dependencies 下添加:
dependencies:
device_info_plus: ^9.0.0
运行 flutter pub get 安装插件。
2. 导入包
在 Dart 文件中导入:
import 'package:device_info_plus/device_info_plus.dart';
3. 获取设备信息
使用 DeviceInfoPlugin 类获取平台相关的设备信息。
Android 设备示例:
DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;
print('设备型号: ${androidInfo.model}');
print('Android 版本: ${androidInfo.version.release}');
print('品牌: ${androidInfo.brand}');
print('设备ID: ${androidInfo.id}');
iOS 设备示例:
IosDeviceInfo iosInfo = await deviceInfo.iosInfo;
print('设备名称: ${iosInfo.name}');
print('系统版本: ${iosInfo.systemVersion}');
print('设备型号: ${iosInfo.model}');
print('UUID: ${iosInfo.identifierForVendor}');
4. 平台判断
通过 Platform 类判断当前平台,避免跨平台错误:
import 'dart:io';
if (Platform.isAndroid) {
// 获取 Android 信息
} else if (Platform.isIOS) {
// 获取 iOS 信息
}
注意事项
- 部分信息(如 Android ID、iOS UUID)可能因设备或权限限制返回
null。
- 在 Android 10+ 中,
androidInfo.id 可能返回固定值,需注意隐私政策。
完整示例可参考 官方文档。