Flutter中使用device_info获取设备信息

1. 安装插件

配置 device_info 插件。

dependencies:
  flutter:
    sdk: flutter

  # 设备信息
  device_info: ^1.0.0

在pubspec.yaml中配置保存后,在VS Code环境中会自动下载依赖包。

如果无法正常下载,执行 flutter pub get 

2. 引入依赖

在需要用到的该插件的文件中引入插件包。

// 引入插件
import 'package:device_info/device_info.dart';

3. 使用插件

苹果设备:

DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();

IosDeviceInfo iosInfo = await deviceInfo.iosInfo;
print('设备唯一标识:${iosInfo.identifierForVendor}'); 
// 更多信息请查看 AndroidDeviceInfo 类中的定义

安卓设备:

DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();

AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;
print('设备唯一标识: ${androidInfo.androidId}');
// 更多信息请查看 IosDeviceInfo 类中的定义

4. 完整示例

import 'package:flutter/material.dart';

// 引入插件
import 'package:device_info/device_info.dart';


class DevicePage extends StatefulWidget {

    DevicePage({Key key}) : super(key: key);

    @override
    _DevicePageState createState() => _DevicePageState();
}

class _DevicePageState extends State<DevicePage> {

    @override
    void initState() {
        super.initState();
        // 获取设备信息
        this._getDeviceInfo();
    }

    void _getDeviceInfo() async{
    
        DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();

        // 安卓系统
        // AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;
        // print('设备唯一标识: ${androidInfo.androidId}');
        // 更多信息请查看 AndroidDeviceInfo 类中的定义

        // 苹果系统
        IosDeviceInfo iosInfo = await deviceInfo.iosInfo;
        print('设备唯一标识:${iosInfo.identifierForVendor}'); 
        // 更多信息请查看 IosDeviceInfo 类中的定义
    }


    @override
    Widget build(BuildContext context) {
        return Container(
            child: Scaffold(
                appBar: AppBar(
                    title: Text("设备信息"),
                ),
            )
        );
    }
}

参考:https://pub.flutter-io.cn/packages/device_info

猜你喜欢

转载自blog.csdn.net/weixin_40629244/article/details/112447169