How to Get DeviceId in Flutter with Example Source Code

How to Get DeviceId in Flutter ?

Hello Guys How are you all ? hope you all are fine. In some case where you need device id in some APIs call like register, login etc. so how to get deviceId in flutter. Lets start this article without wasting your time.

How to Get DeviceId in Flutter with Example Source Code
  • Install device_id Package and put in dependencies in pubspec.yaml file. As like blelow.
dependencies:
  flutter:
    sdk: flutter
  device_id: ^0.2.0
  • Get the dependencies by command pub get.
  • Now you are ready to use this plugin.
  • First of all define variable DeviceId in file where you want to use device_id as like below
String deviceID;
  • Now make method that will return you device_id as string same like below
void getDeviceID() async {
  String deviceId = await DeviceId.getID;
  deviceID = 'Device ID is $deviceId';
  print('Device ID is $deviceId');
}
  • Now, Trigger this method in initState so you will get device_id when initstate will build.
@override
void initState() {
  // TODO: implement initState
  super.initState();
  getDeviceID();
}
  • That’s it. Now you can use Device_id any where, also you can add DeviceId in setState so it can use anywhere I am pasting my full source code here.
import 'package:device_id/device_id.dart';
import 'package:flutter/material.dart';

class GetDeviceId extends StatefulWidget {
  @override
  _GetDeviceIdState createState() => _GetDeviceIdState();
}

class _GetDeviceIdState extends State<GetDeviceId> {
  @override
  String deviceID;

  void getDeviceID() async {
    String deviceId = await DeviceId.getID;
    deviceID = 'Device ID is $deviceId';
    print('Device ID is $deviceId');
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getDeviceID();
  }

  @override
  Widget build(BuildContext context) {
    getDeviceID();
    return MaterialApp(
      home: Scaffold(
        appBar: new AppBar(
          title: const Text('How to Get DeviceId'),
        ),
        body: Center(
          child: Text('$deviceID'),
        ),
      ),
    );
  }
}
How to get DeviceId in flutter ?

In Some Cases where you need a device id in some API call like Register, Login and etc. So let’s Start this article without wasting your time. First of all, install the device_id package and put in dependencies in pubspec.yaml.

So Guys That’s it For How To Get deviceId in Flutter. Comment below Your thoghts and your quries.

Also Read How to create a modal bottomsheet in Flutter?

Milan Dhameliya is an Information Technology Engineer. By profession, he is a Full Stack developer with knowledge of multiple back-end platforms (e.g., PHP, Node.js, Python) and frontend Flutter frameworks.

Leave a Comment