Flutter get device name

Flutter Get Device Name

To retrieve the device name in Flutter, you can use the `device_info` package. This package provides access to various information about the current device, including the device name.

Step 1: Add the `device_info` package to your pubspec.yaml file

In your Flutter project, open the `pubspec.yaml` file and add the following line under the `dependencies` section:

device_info: ^2.0.0

Step 2: Install the package

After adding the package to your pubspec.yaml file, run the following command in your terminal to install the package:

flutter pub get

Step 3: Import the necessary packages

In the Dart file where you want to retrieve the device name, import the following packages:

import 'package:device_info/device_info.dart';

Step 4: Retrieve the device name

Inside a function or method, create an instance of the `DeviceInfoPlugin` class and use its `androidInfo` or `iosInfo` property to get the device name based on the platform:

String getDeviceName() {
  DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();

  if (Platform.isAndroid) {
    AndroidDeviceInfo androidInfo = deviceInfo.androidInfo;
    return androidInfo.model;
  } else if (Platform.isIOS) {
    IosDeviceInfo iosInfo = deviceInfo.iosInfo;
    return iosInfo.name;
  }

  return 'Unknown';
}

The `getDeviceName` function will return the device name as a `String` for both Android and iOS platforms. If the platform is neither Android nor iOS, it will return ‘Unknown’.

Step 5: Use the device name

Call the `getDeviceName` function wherever you need to use the device name. For example:

String deviceName = getDeviceName();
print('Device name: $deviceName');

This will print the device name to the console.

Leave a comment