How to Implement NFC in Flutter: A Beginner’s Guide

CodeTrade
10757 Views

Near-field communication (NFC) is a wireless technology that allows devices to exchange data over short distances. NFC is used in a variety of applications, such as contactless payments, mobile wallets, and access control systems.

In this blog post, we will show you how to implement NFC in Flutter using the nfc_manager package. We will also show you how to use NFC to transfer peer-to-peer data between two devices.

Introduction of NFC in Flutter

NFC peer-to-peer data transfer is a great way to quickly and easily share data between two devices. It is especially useful for sharing small amounts of data, such as contact information or a link to a website.

To implement NFC peer-to-peer data transfer in Flutter, you will need to use the nfc_manager package. This package provides a simple and easy-to-use interface for interacting with NFC devices.

The nfc_manager package does not support peer-to-peer file transfer. This means that if you want to share a photo or other data from one device to another using NFC, you will need to use an NFC tag. This can be a major inconvenience, especially if you want to share data quickly and easily.

There are a few ways to work around the lack of peer-to-peer file transfer support in the nfc_manager package. One way is to use an NFC tag to act as a bridge between the two devices. NFC tags are small, disposable devices that can store a small amount of data. Most NFC tags have a storage limit of 512 KB. This means that you can only use NFC tags to transfer small files, such as photos or contact cards.

If you need to transfer a larger file, such as a video or audio file, you will need to use a different method, such as Bluetooth or Wi-Fi. Let’s explore the process of transferring peer-to-peer data using the NFC_manager package.

Also read: Empower Your App Development with Top-Rated Flutter Developers

Advanced NFC Features

Advanced NFC features are beyond the simple tap-to-pay functionality that most people are familiar with. These features allow deeper interaction between NFC tags and devices and it requires Android Developers to implement. Here we take the scenario of advanced NFC for Android devices.

Working with Different Tag Technologies

When dealing with NFC tags with Android devices, the primary format for data exchange is NDEF (NFC Data Exchange Format). NDEF messages are easily parsed by Android and delivered as a NdefMessage object. However, there are situations where:

  • The scanned tag doesn't contain NDEF data.

  • The NDEF data can't be mapped to a standard format (MIME type or URI).

In these cases, you need to directly communicate with the tag using your protocol (raw bytes). Android provides the android.nfc.tech package for such scenarios. This package offers various classes representing different tag technologies (e.g., NfcA, NfcF). You can use the getTechList() method to identify the technologies supported by a scanned tag and then create the corresponding TagTechnology object for interaction.


Supported Tag Technologies
  • NfcA - Access to NFC-A(ISO 14443-3A) properties and I/O operations.
  • NfcB - Access to NFC-B(ISO 14443-3B) properties and I/O operations.
  • NfcF - Access to NFC-F(JIS 6319-4) properties and I/O operations.
  • NfcV - Access to NFC-V(ISO 15693) properties and I/O operations.
  • IsoDep - Access to ISO-DEP(ISO 14443-4) properties and I/O operations.
  • Ndef - Access to NDEF data for tags formatted as NDEF.
  • NdefFormatable - Provides formatting operations for tags that can be formatted as NDEF.

Reading and Writing to Tags

Reading and writing to NFC tags involves obtaining the Tag object from the intent and opening communication with the tag. Developers can define their protocol stack to read and write data to the tag, or they can still utilize NDEF data for reading and writing. This opens up possibilities for more complex data exchange with compatible tags.

Key Components of NFC Flutter Kit

Flutter itself doesn't have built-in NFC functionality, but there are popular packages that add this capability. One such package is the Flutter NFC Kit. Flutter NFC Kit is a package designed to assist Flutter developers in integrating NFC functionality into their applications. It provides versatile APIs that support a wide array of NFC operations on both Android and iOS platforms. Several key components for working with NFC in your Flutter app:

  • NFC Tag Reading and Writing

    This is the core functionality that allows your app to interact with NFC tags. Flutter NFC Kit enables reading and writing data encoded in NDEF (NFC Data Exchange Format), the universal format for NFC communication.

  • NFC Session Management

    The NFC Kit handles initiating and stopping NFC sessions on the device. An NFC session is essentially a period when the app is actively listening for and ready to interact with NFC tags brought into proximity.

  • NDEF Message Support

    NDEF messages are how data is encoded on NFC tags. The Flutter NFC Kit allows you to create and parse NDEF messages for various data types like text, URIs, or even launch commands for your app.

  • Seamless integration with Flutter

    This plugin seamlessly integrates with both Android and iOS Flutter applications. Developers can easily incorporate NFC functionality into their apps with minimal changes to their existing codebase.

Implementation of NFC in Flutter To Transfer Peer-to-peer Data Using The Nfc_manager Package

To implement NFC in Flutter to transfer peer-to-peer data using the nfc_manager package, you will need to:

1. Add nfc_manager Package in Flutter

To transfer peer-to-peer data using the nfc_manager package, you must first add it to your Flutter project. You can do this by running the following command in the root directory of your project:

flutter pub add nfc_manager

Once the package is installed, you can import it into your Flutter code and start using it to access the NFC features on Android and iOS.

2. Configure Permissions

You will need to configure the necessary permissions in both the Android and iOS applications:

Android
  • Open your AndroidManifest.xml file. Add the following permission:

    <uses-permission android:name="android.permission.NFC">
  • Save the file.
iOS
  • Open your Info.plist file. Add the following key-value pair:

    <key>NFCReaderUsageDescription</key>
    <string>Your explanation of why the app needs NFC</string>
  • Save the file.

Once you have configured the necessary permissions, you can start using the nfc_manager package to access the NFC features on Android and iOS.

3. Read NFC Tags

To read an NFC tag, you first need to check if NFC is available. Then check the availability, and initiate an NFC session using NfcManager.instance.startSession(). When an NFC tag is discovered, you can print its data to the console or handle it in your way. Let’s check the full example of Read NFC Tag data.

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

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  const MyHomePage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('NFC Reader'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: _startNFCReading,
          child: const Text('Start NFC Reading'),
        ),
      ),
    );
  }

  void _startNFCReading() async {
    try {
      bool isAvailable = await NfcManager.instance.isAvailable();

      //We first check if NFC is available on the device.
      if (isAvailable) {
      //If NFC is available, start an NFC session and listen for NFC tags to be discovered.
        NfcManager.instance.startSession(
          onDiscovered: (NfcTag tag) async {
            // Process NFC tag, When an NFC tag is discovered, print its data to the console.
            debugPrint('NFC Tag Detected: ${tag.data}');
          },
        );
      } else {
        debugPrint('NFC not available.');
      }
    } catch (e) {
      debugPrint('Error reading NFC: $e');
    }
  }
}

This code will check if NFC is available on the device. If it is, the code will start an NFC session and listen for NFC tags. When an NFC tag is discovered, the code will print the data from the tag to the console.

4. Write NFC Tags

Writing NFC tags store data on an NFC tag. To write an NFC tag, you will need a blank NFC tag and an NFC writer. NFC writers are devices that can read and write NFC tags. Some NFC writers are built into smartphones, while others are external devices that connect to your computer. Let’s check the complete example of how to write an NDEF record to an NFC tag:

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

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  const MyHomePage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('NFC Writer'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: _startNFCWriting,
          child: const Text('Start NFC Writing'),
        ),
      ),
    );
  }

  void _startNFCWriting() async {
    try {
# check if NFC is available on the device or not.
      bool isAvailable = await NfcManager.instance.isAvailable();

# If NFC is available, start a session to listen for NFC tags.
      if (isAvailable) { 
 NfcManager.instance.startSession(onDiscovered: (NfcTag tag) async {

        try {
# When an NFC tag is discovered, we check if it supports NDEF technology.
          NdefMessage message =
              NdefMessage([NdefRecord.createText('Hello, NFC!')]);
          await Ndef.from(tag)?.write(message);//If it supports NDEF, create an NDEF message and write it to the tag.
          debugPrint('Data emitted successfully');
          Uint8List payload = message.records.first.payload;
          String text = String.fromCharCodes(payload);
          debugPrint("Written data: $text");

#stop the NFC Session
          NfcManager.instance.stopSession();
        } catch (e) {
          debugPrint('Error emitting NFC data: $e');
        }
      });
      } else {
        debugPrint('NFC not available.');
      }
    } catch (e) {
      debugPrint('Error writing to NFC: $e');
    }
  }
}

This code will write an NDEF record with the text "hello" to the NFC tag. You can modify the code to write any type of data to the NDEF record.

Once you have written data to an NFC tag, you can share it with other devices by tapping the tags together. The other device can then read the data from the tag using an NFC reader app.

That’s it…! Using this simple code you can simply implement NFC in Flutter to transfer peer-to-peer data using the nfc_manager package.

Conclusion

This is just a brief introduction to how to implement NFC in Flutter. For more information, you can refer to the nfc_manager documentation: https://pub.dev/packages/nfc_manager.

In this blog, we’ll explain the possibilities of transferring peer-to-peer data using the nfc_manager package with an example. Using the given code you can simply implement NFC in your flutter project.

Need help with NFC in Flutter? CodeTrade India, a top mobile app development company in India, can help you implement NFC in Flutter. We have a team of experienced Flutter developers who can assist you with your project. Hire a dedicated Flutter developer from CodeTrade today!

CodeTrade
CodeTrade, a Custom Software Development Company, provides end-to-end SME solutions in USA, Canada, Australia & Middle East. We are a team of experienced and skilled developers proficient in various programming languages and technologies. We specialize in custom software development, web, and mobile application development, and IT services.