详解如何在Flutter中获取设备标识符_Android_

2022年4月13日11:06:18

本文将引导您完成 2 个示例,演示如何在 Flutter 中获取设备标识符

使用 platform_device_id

如果您只需要运行应用程序的设备的 id,最简单快捷的解决方案是使用platform_device_id包。它适用于 Android (AndroidId)、iOS (IdentifierForVendor)、Windows (BIOS UUID)、macOS (IOPlatformUUID) 和 Linux (BIOS UUID)。在 Flutter Web 应用程序中,您将获得 UserAgent(此信息不是唯一的)。

应用预览

我们要构建的示例应用程序包含一个浮动按钮。按下此按钮时,设备的 ID 将显示在屏幕上。以下是它在 iOS 和 Android 上的工作方式:

代码

1.通过运行安装插件:

flutter pub add platform_device_id

然后执行这个命令:

flutter pub get

不需要特殊权限或配置。

2.完整代码:

// main.dart
import 'package:flutter/material.dart';
import 'package:platform_device_id/platform_device_id.dart';
​
void main() {
  runApp(const MyApp());
}
​
class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        // Remove the debug banner
        debugShowCheckedModeBanner: false,
        title: '大前端之旅',
        theme: ThemeData(
          primarySwatch: Colors.indigo,
        ),
        home: const HomePage());
  }
}
​
class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);
​
  @override
  _HomePageState createState() => _HomePageState();
}
​
class _HomePageState extends State<HomePage> {
  String? _id;
​
  // This function will be called when the floating button is pressed
  void _getInfo() async {
    // Get device id
    String? result = await PlatformDeviceId.getDeviceId;
​
    // Update the UI
    setState(() {
      _id = result;
    });
  }
​
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('大前端之旅')),
      body: Padding(
        padding: const EdgeInsets.all(20),
        child: Center(
            child: Text(
          _id ?? 'Press the button',
          style: TextStyle(fontSize: 20, color: Colors.red.shade900),
        )),
      ),
      floatingActionButton: FloatingActionButton(
          onPressed: _getInfo, child: const Icon(Icons.play_arrow)),
    );
  }
}

使用 device_info_plus

device_info_plus为您提供作为 platform_device_id 的设备 ID,并提供有关设备的其他详细信息(品牌、型号等)以及 Flutter 应用运行的 Android 或 iOS 版本。

应用预览

我们将制作的应用程序与上一个示例中的应用程序非常相似。但是,这一次我们将在屏幕上显示大量文本。返回的结果因平台而异。如您所见,Android 上返回的信息量远远超过 iOS。

代码

1. 通过执行以下操作安装插件:

flutter pub add device_info_plus

然后运行:

flutter pub get

2. main.dart中的完整源代码:

// main.dart
import 'package:flutter/material.dart';
import 'package:device_info_plus/device_info_plus.dart';
​
void main() {
  runApp(const MyApp());
}
​
class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        // Remove the debug banner
        debugShowCheckedModeBanner: false,
        title: '大前端之旅',
        theme: ThemeData(
          primarySwatch: Colors.amber,
        ),
        home: const HomePage());
  }
}
​
class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);
​
  @override
  _HomePageState createState() => _HomePageState();
}
​
class _HomePageState extends State<HomePage> {
  Map? _info;
​
  // This function is triggered when the floating button gets pressed
  void _getInfo() async {
    // Instantiating the plugin
    final deviceInfoPlugin = DeviceInfoPlugin();
​
    final result = await deviceInfoPlugin.deviceInfo;
    setState(() {
      _info = result.toMap();
    });
  }
​
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('大前端之旅')),
      body: _info != null
          ? Padding(
              padding: const EdgeInsets.all(20),
              child: ListView(
                children: _info!.entries
                    .map((e) => Wrap(
                          children: [
                            Text(
                              "${e.key} :",
                              style: const TextStyle(
                                  fontSize: 18, color: Colors.red),
                            ),
                            const SizedBox(
                              width: 15,
                            ),
                            Text(
                              e.value.toString(),
                              style: const TextStyle(
                                fontSize: 18,
                              ),
                            )
                          ],
                        ))
                    .toList(),
              ),
            )
          : const Center(
              child: Text('Press the button'),
            ),
      floatingActionButton: FloatingActionButton(
        onPressed: _getInfo,
        child: const Icon(Icons.info),
      ),
    );
  }
}

结论

我们已经介绍了几种读取设备信息的技术。选择一个适合您在项目中实施的需求。

  • 作者:大前端之旅  
  • 原文链接:https://juejin.cn/post/7084259406421950495
    更新时间:2022年4月13日11:06:18 ,共 3256 字。