Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Key Widgets
  • UI Components
  • Design & Animations
  • Forms & Gestures
  • Navigation & Routing
  • Flutter Interview Questions
  • Dart
  • Android
  • Kotlin
  • Kotlin Android
  • Android with Java
  • Android Studio
Open In App
Next Article:
Creating a Simple Application in Flutter
Next article icon

How to Create a NFC Reader and Writer Flutter Application

Last Updated : 25 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

NFC that stands for Near Field Communication, is a very short range wireless technology that allows us share small amount of data between devices. Through this technology we can share data between an NFC tag and an android device or between two android devices. A maximum of 4 cm distance is required to establish this connection. In this articles, we will be developing a basic application that involved communicating between an Android Device and a NFC Tag.

Prerequisites

  1. NFC-Enabled Android Device - Your device must support NFC.
  2. Android Studio  or Visual Studio Code- Install Android Studio or Visual Studio Code in your System.
  3. Basic Knowledge of Flutter & dart - We will be developing this app using the Flutter & Dart.
  4. NFC Tag - You must have a NFC tag, sticker or a card for testing purposes.

Steps to Create a NFC Reader and Writer Android Application

Step 1: Create a New Project in Android Studio or Visual Studio Code.

To create a new project in Android Studio please refer to Creating a Simple Application in Flutter.

Step 2: In your flutter project open pubspec.yaml and under dependencies add the following packages:

dependencies:
flutter:
sdk: flutter
nfc_manager: ^3.5.0

To know more about package refer : nfc_manager

Step 3: Adding Permissions in Manifest File

Navigate to android > app > src > main > AndroidManifest.xml and add the following permissions under the manifest tag.

<uses-permission android:name="android.permission.NFC"  />
<uses-feature android:name="android.hardware.nfc" android:required ="true" />


Step 3: Working with main.dart

main.dart include 3 primary functionalities to execute NFC in flutter application.

  • Check the device is compatible with NFC or Not
  • Read data using NFC
  • Write data using NFC

- Check the device is compatible with NFC or not.

Dart
 NfcManager.instance.isAvailable().then((isAvailable) {     if (isAvailable) {         print("availble"); // Start NFC session if available     } else {         print("unavailble"); // Show error message if NFC is not available       } }); 


- Read data using NFC

Dart
// Function to read NFC tag void _readNfcTag() {     //Start NFC session     NfcManager.instance.startSession(onDiscovered: (NfcTag tag) async {       Ndef? ndef = Ndef.from(tag);       if (ndef != null) {         // Read message from tag         NdefMessage? message = await ndef.read();          //Code to Store the fetched data from tag         ....       }       // Stop NFC session       NfcManager.instance.stopSession();      });   } 


- Write data using NFC

Dart
void _writeNfcTag() {     // Start NFC session     NfcManager.instance.startSession(onDiscovered: (NfcTag tag) async {       // Example of writing data to the tag       Ndef? ndef = Ndef.from(tag);       if (ndef != null && ndef.isWritable) {         // Create NDEF message with input text         NdefMessage message = NdefMessage([           NdefRecord.createText(String_data),          ]);         // Write message to tag         await ndef.write(message);        }       // Stop NFC session       NfcManager.instance.stopSession();      }); } 


The whole Application code for this is provided below:

main.dart:

Dart
import 'package:flutter/material.dart'; import 'package:nfc_manager/nfc_manager.dart';  void main() {        // Start the app   runApp(const MyApp());  }  class MyApp extends StatelessWidget {   const MyApp({super.key});    @override   Widget build(BuildContext context) {     return MaterialApp(       debugShowCheckedModeBanner: false, // Hide the debug banner       home: NfcScreen(), // Set the home screen to BitCoinTracker     );   } }  // Main class for the NFC screen class NfcScreen extends StatefulWidget {   @override   _NfcScreenState createState() => _NfcScreenState(); }  // State class for the NFC screen class _NfcScreenState extends State<NfcScreen> {   // Variable to store NFC data   String _nfcData = 'No data';       // Controller for text input   final TextEditingController _textController = TextEditingController();       @override   void initState() {     super.initState();          // Check if NFC is available     NfcManager.instance.isAvailable().then((isAvailable) {       if (isAvailable) {         // Start NFC session if available       }        else {         setState(() {                         // Update UI if NFC is not available            _nfcData = 'NFC is not available';          });       }     });   }    // Function to start NFC session   void _writeNfcTag() {            // Start NFC session     NfcManager.instance.startSession(onDiscovered: (NfcTag tag) async {              // Example of writing data to the tag       Ndef? ndef = Ndef.from(tag);              if (ndef != null && ndef.isWritable) {                  // Create NDEF message with input text         NdefMessage message = NdefMessage([           NdefRecord.createText(_textController.text),         ]);         try {           // Write message to tag           await ndef.write(message);           setState(() {               // Update UI on success               _nfcData = 'Write successful!';            });         } catch (e) {           setState(() {               // Update UI on failure               _nfcData = 'Write failed: $e';            });         }       }              // Stop NFC session       NfcManager.instance.stopSession();     });   }    // Function to read NFC tag   void _readNfcTag() {     NfcManager.instance.startSession(onDiscovered: (NfcTag tag) async {       Ndef? ndef = Ndef.from(tag);       if (ndef != null) {         // Read message from tag         NdefMessage? message = await ndef.read();                  setState(() {                        // Store payload in temp variable           var rawData = message.records.first.payload;                       // Convert payload to string           String textData = String.fromCharCodes(rawData);                       // Update UI with read data           _nfcData = textData.substring(3);          });       }              // Stop NFC session       NfcManager.instance.stopSession();     });   }    @override   Widget build(BuildContext context) {     return Scaffold(       appBar: AppBar(         title: Text('NFC Screen'), // App bar title       ),       body: Padding(         padding: const EdgeInsets.all(20),         child: Column(           mainAxisAlignment: MainAxisAlignment.center,           children: [             TextField(               controller: _textController,               decoration: InputDecoration(                 labelText: 'Enter data to write', // Input field label               ),             ),             ElevatedButton(               onPressed: _writeNfcTag,               child: Text('Write to NFC'), // Button to write to NFC             ),             ElevatedButton(               onPressed: _readNfcTag,               child: Text('Read from NFC'), // Button to read from NFC             ),             SizedBox(height: 20),             Text(_nfcData), // Display NFC data           ],         ),       ),     );   } } 


Output:

Note : default NFC reader can pop-up in your screen. So, the solution is preventing default Android NFC reader.

Solution of the above Problem

If you get any uneven behavior of the app like opening a default pop-up in the middle of the process then to control that behavior add below code in android > app > src > main > kotlin > com > example > oyo > MainActivity.kt.

MainActivity.kt:

Kotlin
package com.example.yourapp import android.app.PendingIntent import android.content.Intent import android.nfc.NfcAdapter import io.flutter.embedding.android.FlutterActivity  class MainActivity: FlutterActivity() {      // This method is called when the     // activity is resumed     override fun onResume() {         super.onResume()                  // Create an intent to restart         // this activity         val intent = Intent(context, javaClass).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)                  // Create a pending intent to be         // used by the NFC adapter         val pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE)                  // Enable NFC foreground dispatch         // to handle NFC tags when the app         // is in the foreground         NfcAdapter.getDefaultAdapter(context)?.enableForegroundDispatch(this, pendingIntent, null, null)     }      // This method is called when the     // activity is paused     override fun onPause() {         super.onPause()         // Disable NFC foreground dispatch         // when the app is not in the foreground         NfcAdapter.getDefaultAdapter(context)?.disableForegroundDispatch(this)     } } 


For GitHub link for the repository for the application is refer to this link.



Next Article
Creating a Simple Application in Flutter

V

vinaylaop3z
Improve
Article Tags :
  • Flutter
  • Flutter Projects

Similar Reads

  • How to Create a Desktop Window Application in Flutter?
    The Flutter team recently released Flutter version 2.10 with Desktop support. Desktop support allows you to compile Flutter source code to a native Windows, macOS, or Linux desktop app. Flutter’s desktop support also extends to plugins—you can install existing plugins that support the Windows, macOS
    3 min read
  • How to Build and Release Flutter Application in Android Device?
    Flutter is Google’s Mobile SDK to build native iOS and Android, Desktop (Windows, Linux, macOS), Web apps from a single codebase. When building applications with Flutter everything towards Widgets – the blocks with which the flutter apps are built. They are structural elements that ship with a bunch
    2 min read
  • Flutter - Read and Write Data on Firebase
    Firebase helps developers to manage their mobile apps easily. It is a service provided by Google. Firebase has various functionalities available to help developers manage and grow their mobile apps. In this article, we will learn how to write and read data into/from Firebase. Follow the 3-step proce
    4 min read
  • How to Build a ToDo Application in Flutter?
    Flutter offers a stable framework for constructing richly UI-driven cross-platform applications. In this article, we will learn to build a ToDo Flutter Application. What is the ToDo Application?The ToDo application helps users manage and organize their tasks and responsibilities more easily. Managin
    6 min read
  • Creating a Simple Application in Flutter
    Flutter is an open-source cross-platform mobile application development SDK created by Google. It is highly user-friendly and builds high-quality mobile applications. The intention behind this article is to guide readers through the process of building an application through Flutter by creating a si
    5 min read
  • Creating a Finance Tracker Application in Flutter
    Developing a new tracker for finance is a good practice to improve your skills and build a helpful application. Through Flutter, an open-source UI toolkit developed by Google, it is possible to design for iOS/ Android, web, and desktop. Here you will find out the recipe of how to create a finance tr
    6 min read
  • EBook reader Application in Flutter
    EBook reader Application brings the library to your fingertips. This application will be the travel partner of every book lover who loves to read books of their choice. The app is developed using Flutter and provider state management. It uses the Google Books API to fetch the data of books. The app
    8 min read
  • How to Run a Flutter App on Android Emulator?
    An emulator is a virtual device created to run programs/applications derived from the host system. An Android Emulator imitates an Android device and is used to run and test Android applications on your host system without requiring the presence of a physical Android device. To run your Flutter appl
    3 min read
  • How to Build Music Player Application Using Flutter?
    Music can inspire and motivate us, it makes every person feel enthusiastic and relaxed. In this article, we will explain how to build a Music Player application step by step with some basic functionalities like pause, play, and seek in Flutter from a music URL. Flutter is an open-source framework de
    6 min read
  • How to Write TestCases For API Calls in Flutter?
    Here we are going to a built app that calls an API and write test cases for it before we dive into it let’s go through some basic concepts. Software testing is a process in which we test code to ensure that it produces the excepted results at any given instance. Flutter tests consist of: Unit test -
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences