How to get the current device information in Flutter

Flutter Jul 28, 2023

In Flutter, the device_info_plus package allows developers to get specific details about a user's device, like the model, operating system version, and manufacturer. This package works across various platforms, including Android, iOS, Linux, macOS, web browsers, and Windows. In this post, we will learn how to install and use the device_info_plus package and explore a practical example for retrieving device information on different platforms.

Installing

To get started with the implementation, we need to install the device_info_plus package into our project. The installation process is simple. Just execute the following command: flutter pub add device_info_plus.

Once the command is executed, make sure to check your pubspec.yaml file for the added dependencies. You should see the device_info_plus package included in the dependencies section, like this:

dependencies:
  device_info_plus: ^9.0.2
  flutter:
    sdk: flutter

Implementation

Now that the device_info_plus package is installed, we will use it to retrieve and display device information in our application. Inside our main.dart file, we have two widgets, MyApp and DeviceInfoScreen. The DeviceInfoScreen contains the logic to retrieve and show the device information. Let us go over the code to understand how to implement the device_info_plus package:

main.dart

import 'package:flutter/material.dart';
import 'package:device_info_plus/device_info_plus.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Device Information App',
      home: DeviceInfoScreen(),
    );
  }
}

class DeviceInfoScreen extends StatefulWidget {
  @override
  _DeviceInfoScreenState createState() => _DeviceInfoScreenState();
}

class _DeviceInfoScreenState extends State<DeviceInfoScreen> {
  String _deviceInfo = '';

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _getDeviceInfo();
  }

  Future<void> _getDeviceInfo() async {
    DeviceInfoPlugin deviceInfoPlugin = DeviceInfoPlugin();
    
    try {
      String deviceInfo = switch (Theme.of(context).platform) {
        TargetPlatform.iOS => await deviceInfoPlugin.iosInfo
            .then((IosDeviceInfo iosInfo) => 'Model: ${iosInfo.model}\n'
                'System Name: ${iosInfo.systemName}\n'
                'System Version: ${iosInfo.systemVersion}\n'
                'Device ID: ${iosInfo.identifierForVendor}\n'),
        TargetPlatform.android => await deviceInfoPlugin.androidInfo.then(
            (AndroidDeviceInfo androidInfo) => 'Brand: ${androidInfo.brand}\n'
                'Model: ${androidInfo.model}\n'
                'Android Version: ${androidInfo.version.release}\n'
                'Device ID: ${androidInfo.id}\n'),
        _ => await deviceInfoPlugin.deviceInfo.then(
            (BaseDeviceInfo deviceInfo) => deviceInfo.data.entries
                .map((entry) => '${entry.key}: ${entry.value}')
                .join('\n')),
      };

      setState(() => _deviceInfo = deviceInfo);
    } catch (error) {
      print('Error getting device info: $error');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Device Information'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(20.0),
        child: Text(
          _deviceInfo,
          style: TextStyle(fontSize: 20),
        ),
      ),
    );
  }
}

In this code snippet, we create a simple application that displays device information for iOS, Android, and other platforms using the device_info_plus package.

We start with the MyApp widget, the root widget of our application. The MyApp widget returns the MaterialApp widget, with the DeviceInfoScreen set as its home screen.

The DeviceInfoScreen is a StatefulWidget responsible for retrieving and displaying the device information on the screen. It holds a private _deviceInfo variable to store the retrieved device information.

When the widget's dependencies change, the didChangeDependencies lifecycle method is called. In this method, the _getDeviceInfo() function is called to retrieve the device information.

The _getDeviceInfo function uses the DeviceInfoPlugin class to get information about the device based on the current platform (Theme.of(context).platform). To determine which information needs to be returned, the function uses a switch expression with cases for iOS and Android and a default case indicated by an underscore (_) for all other platforms.

  • For iOS devices, it retrieves IosDeviceInfo and displays its properties (model, systemName, systemVersion, and identifierForVendor) as a formatted string.

IosDeviceInfo properties:

  • Map<String, dynamic> data: Device information data (Warning: The returned Map may not be JSON-encodable).
  • String? identifierForVendor: Unique UUID value identifying the current device.
  • bool isPhysicalDevice: false if the application is running in a simulator, true otherwise.
  • String localizedModel: Localized name of the device model.
  • String model: Device model.
  • String name: Device name.
  • String systemName: The name of the current operating system.
  • String systemVersion: The current operating system version.
  • IosUtsname utsname: Operating system information derived from sys/utsname.h.

  • For Android devices, it retrieves AndroidDeviceInfo and displays its properties (brand, model, version, and id) as a formatted string.

AndroidDeviceInfo properties:

  • String board: The name of the underlying board, like "goldfish" for the Android emulator.
  • String bootloader: The system bootloader version number
  • String brand: The brand of the device.
  • Map<String, dynamic> data: Device information data (Warning: The returned Map may not be JSON-encodable).
  • String device: The name of the industrial design.
  • String display: The display name of the device.
  • AndoirdDisplayMetrics displayMetrics: Information about the current Android display.
  • String fingerprint: The device's fingerprint.
  • String hardware: The hardware name of the device.
  • String host: Hostname.
  • String id: The unique ID of the device.
  • String isPhysicalDevice: Whether the app is running on a physical device or not.
  • String manufacturer: The manufacturer of the device.
  • String model: The model name of the device.
  • String product: The product name of the device.
  • String SerialNumber: Hardware serial number of the device, if available.
  • List<String> systemFeatures: Describes what features are available on the current device.
  • String tags: Comma-separated tags describing the build, like "release-keys".
  • String type: The build type, like "user" or "eng".
  • String version: The version of the Android OS.
  • For other platforms (non-iOS and non-Android), it retrieves BaseDeviceInfo, extracts its data entries, and displays them as a formatted string.

After the device information is retrieved, it is stored in the _deviceInfo variable. To catch any potential errors the function uses a try-catch to print them to the console.

The build method of DeviceInfoScreen returns a Scaffold with an AppBar and a Text widget displaying the device information. The retrieved device information is displayed in a font size of 20 and is wrapped inside some padding for better presentation.

When we run the application on an Android emulator, we will see the following results:

flutter_displayer_device_information_on_android_emulator

When we run the application in the browser using the command flutter run -d chrome, it will trigger the default case in our switch expression. This default case provides information with the BaseDeviceInfo type.

flutter_displayer_device_information_on_chrome_web_browser

However, when we check the properties, they match the properties available from the WebBrowserInfo class. This is because the DeviceInfoPlugin class of the device_info_plus package has detected that we are running the application in the browser.

WebBrowserInfo properties:

  • String? appCodeName: The code name of the browser application. Note: Do not rely on this property to return the correct value.
  • String? appName: The official name of the browser application. Note: Do not rely on this property to return the correct value.
  • String? appVersion: The version of the browser application. Note: Do not rely on this property to return the correct value.
  • BrowserName browserName: The name of the current browser.
  • Map<String, dynamic> data: Device information data (Warning: The returned Map may not be JSON-encodable).
  • int? deviceMemory: The amount of device memory in gigabytes.
  • int? hardwareConcurrency: The number of processor cores available
  • String? language: The preferred language of the user in the browser application.
  • List? languages: A list of known languages by the user in the browser application.
  • int? maxTouchPoints: The maximum number of simultaneous touch contact points that are supported by the current device.
  • String? platform: The platform on which the browser application is running. Note: Do not rely on this property to return the correct value.
  • String? product: Always returns 'Gecko', on any browser. Note: Do not rely on this property to return the correct value. This property is kept only for compatibility purposes.
  • String? productSub: The build number of the current browser. Note: Do not rely on this property to return the correct value.
  • String? userAgent: The user agent string of the browser application.
  • String? vendor: The vendor name of the browser application.
  • String? vendorSub: Returns the vendor version number. Note: Do not rely on this property to return the correct value.

Available Device information platforms

The device_info_plus package in Flutter supports various platforms to access specific device information for different operating systems and devices. We already used three of them in the above example. To make this post complete I have included all the them in the list below:

  • AndroidDeviceInfo: Provides device information for Android devices, such as the brand, model, hardware details, system version, and many other device-specific attributes.
  • BaseDeviceInfo: Serves as the base class for device information on various platforms. It includes common device properties shared across different platforms, such as the device name, model, and operating system version.
  • IosDeviceInfo: Offers detailed device information for iOS devices, such as the model, system version, device name, and other iOS-specific attributes.
  • LinuxDeviceInfo: Provides device information specific to Linux-based systems, including details about the machine, kernel, and other Linux-specific attributes.
  • MacOsDeviceInfo: Offers device information relevant to macOS-based systems, such as the model, version, and other macOS-specific attributes.
  • WebBrowserInfo: Contains information about the web browser being used, including the browser name, version, and other browser-specific details.
  • WindowsDeviceInfo: Provides device information specific to Windows-based systems, including details about the device, manufacturer, and other Windows-specific attributes.

Conclusion

The device_info_plus package is a very convenient tool for Flutter developers to access device-specific data. By using this package, you can retrieve important details about users' devices, like the model and operating system version, across different platforms. Now that you know how to use the device_info_plus package, you can create flexible and user-friendly applications that adapt to different devices.

Tags