How to Get the Current Device Information in Flutter

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.
  • For Android devices, it retrieves AndroidDeviceInfo and displays its properties (brand, model, version, and id) as a formatted string.
  • 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:

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.

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.

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.

Tijn van den Eijnde
Tijn van den Eijnde
Articles: 85

Leave a Reply

Your email address will not be published. Required fields are marked *