How to Device ID in flutter
How to Device ID in flutter

Hi Guys, Welcome to Proto Coders Point, In this flutter tutorial article we will learn how to get deviceID in flutter.

We will checkout, both the ways to get deviceId in flutter

  1. Get DeviceID using Plugin – PlatformDeviceId
  2. Flutter get deviceId without using any plugin

1. Method – Using PlatformDeviceId plugin/packages

Step 1: Install plugin using pubspec.yaml file

dependencies:
  platform_device_id: #keep empty to take latest version

Step 2: Import the platform_device_id.dart class

import 'package:platform_device_id/platform_device_id.dart';

Step 3: Create a function and call it to get deviceID

Future<void> getDeviceIDUsingPlugin() async {
        deviceId = await PlatformDeviceId.getDeviceId;
        print(deviceId);
}

2. Method – Without using plugin get flutter device ID

Learn more on How to call android native code from flutter

In below code’s we will call android native code, that return mobile flutter unique device id. To acheive this we will make use of MethodChannel to communicate with android native code.

Flutter get mac address without usi...
Flutter get mac address without using plugin - get_mac
Flutter Code – main.dart

import 'package:flutter/material.dart';
import 'package:flutter/services.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(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
      debugShowCheckedModeBanner: false ,
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  static const Channel = MethodChannel('com.example.getdID');
  String? deviceId;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Get Device ID"),
        centerTitle: true,
      ),
         body: Center(
           child: Column(
             mainAxisAlignment: MainAxisAlignment.center,
             children: [
               ElevatedButton(onPressed: (){
                 getDeviceID(); 
                 },child: const Text("Without using Plugin - Flutter Get Device ID"),),
             ],
           ),
         )
    );
  }
      //call android native code
     Future<void> getDeviceID() async {
          String deviceID = await Channel.invokeMethod('getDeviceId');
          print(deviceID);
      }
      
}

Android module code – MainActivity.kt

package com.example.backpress

import android.provider.Settings
import android.util.Log
import android.widget.Toast
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
import java.lang.reflect.Method
import java.net.NetworkInterface
import java.util.*

class MainActivity: FlutterActivity() {

    private  val CHANNEL = "com.example.getdID";

    private  lateinit var channel: MethodChannel

    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)

        channel = MethodChannel(flutterEngine.dartExecutor.binaryMessenger,CHANNEL)

        channel.setMethodCallHandler { call, result ->

            if(call.method == "getDeviceId"){
                var dID = Settings.Secure.getString(applicationContext.contentResolver,Settings.Secure.ANDROID_ID);
                result.success(dID);
                Toast.makeText(this, dID, Toast.LENGTH_LONG).show()

            }
        }
    }
}



Complete Source Code to get device ID in flutter

Complete project source code – how to get device id in flutter, with & without using plugin.

main.dart

import 'package:flutter/material.dart';
import 'package:flutter/services.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(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
      debugShowCheckedModeBanner: false ,
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  static const Channel = MethodChannel('com.example.getdID');

  String? deviceId;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Get Device ID"),
        centerTitle: true,
      ),
         body: Center(
           child: Column(
             mainAxisAlignment: MainAxisAlignment.center,
             children: [
               ElevatedButton(onPressed: (){
                 getDeviceID();
                 },child: const Text("Without using Plugin - Flutter Get Device ID"),),
               const SizedBox(
                 height: 15,
               ),
               ElevatedButton(onPressed: () {
                 getDeviceIDUsingPlugin();

               },child: const Text("By Using PlatformDeviceId Plugin- Flutter Get Device ID"),),
             ],
           ),
         )
    );
  }

      // This function calls android native code using methodchannel and invokeMethod.
     Future<void> getDeviceID() async {
          String deviceID = await Channel.invokeMethod('getDeviceId');
          print(deviceID);
      }

  // deviceid using plugin
  Future<void> getDeviceIDUsingPlugin() async {
    deviceId = await PlatformDeviceId.getDeviceId;
    print(deviceId);
  }


}