Find The Latest Tech Insights, News and Updates to Read

How To Implement NFC in Flutter App: A Step-by-Step Tutorial

Written by Achin Verma | Sep 6, 2024 11:52:54 AM

Introduction

What is Flutter?

Flutter is an open-source UI toolkit developed by Google for building natively compiled applications for mobile, web, and desktop from a single codebase. It leverages the Dart programming language and provides a rich set of pre-designed widgets for crafting high-performance, visually appealing apps.

What is NFC?

Near Field Communication (NFC) is a set of communication protocols that enables devices to exchange data over short distances, typically up to 10 cm. NFC is commonly used for tasks such as mobile payments, ticketing, and data exchange between devices.

Integrating NFC with Flutter: Key Steps

1. Add Dependencies

To work with NFC in a Flutter application, use the nfc_manager package. Add the package to your pubspec.yaml:

dependencies:

flutter:
    sdk: flutter
  nfc_manager: ^3.0.0  # Check for the latest version

Run flutter pub get to install the dependency.

 

Short on time? Speed things up with YTII. Hire our skilled Futter app developers to create innovative and engaging mobile experiences. 

2. Configure Platform-Specific Settings

For iOS:

Open ios/Runner/Info.plist and add the following configuration to request NFC permissions:

<key>NSNFCUsageDescription</key>
<string>We need NFC access to scan tags.</string>

 

Ensure you have NFC capabilities enabled in your Xcode project:

Open Xcode and select your project.

Go to the "Signing & Capabilities" tab.

Add the "Near Field Communication Tag Reading" capability.

For Android:

Open android/app/src/main/AndroidManifest.xml and add the following permissions and features:

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

 

Ensure NFC support is declared in your build.gradle:

android {
    defaultConfig {
        ...
        minSdkVersion 19  // NFC requires at least API level 19
    }
}

3. Implement NFC Functionality

Use the nfc_manager package to handle NFC operations such as reading and writing NFC tags.

Here’s an example of reading an NFC tag:

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

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: NfcScreen(),
    );
  }
}

class NfcScreen extends StatefulWidget {
  @override
  _NfcScreenState createState() => _NfcScreenState();
}

class _NfcScreenState extends State<NfcScreen> {
  String _nfcData = 'Scan a tag';

  @override
  void initState() {
    super.initState();
    _startNfcScan();
  }

  void _startNfcScan() async {
    NfcManager.instance.startSession(
      onDiscovered: (NfcTag tag) {
        final ndef = Ndef.from(tag);
        if (ndef != null) {
          ndef.read().then((NdefMessage message) {
            setState(() {
              _nfcData = message.records.map((record) => String.fromCharCodes(record.payload)).join();
            });
          });
        } else {
          setState(() {
            _nfcData = 'NDEF not supported';
          });
        }
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('NFC Reader')),
      body: Center(
        child: Text(_nfcData),
      ),
    );
  }
}

4. Write to NFC Tags

To write data to an NFC tag, you can use the following code snippet:

void _writeNfcTag() async {
  NfcManager.instance.startSession(
    onDiscovered: (NfcTag tag) async {
      final ndef = Ndef.from(tag);
      if (ndef != null) {
        final ndefMessage = NdefMessage([
          NdefRecord.createText('Hello, NFC!'),
        ]);
        await ndef.write(ndefMessage);
        setState(() {
          _nfcData = 'Data written to tag!';
        });
      } else {
        setState(() {
          _nfcData = 'NDEF not supported';
        });
      }
    },
  );
}

 

Summary

  • Add Dependencies: Use the nfc_manager package to handle      NFC operations.
  • Configure Platforms: Set up NFC permissions and capabilities for iOS and Android.
  • Implement NFC: Use the package to read from and write to NFC tags.

Integrating NFC into your Flutter application allows you to leverage modern, secure, and convenient ways to interact with physical objects, enhancing user experience through seamless data exchange and interaction.