How to Invoke an Alert Dialog with Confirm to Redirect After Scanning a QR Code?


BarcodeBC > Articles > How to Invoke an Alert Dialog with Confirm to Redirect After Scanning a QR Code?


Invoke an Alert Dialog with Confirm to Redirect After Scanning a QR Code in an Android App

To invoke an alert dialog with a confirm to redirect after scanning a QR Code in an Android app, you can use the following code.


AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Confirm Redirect");
builder.setMessage("Do you want to be redirected?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        // Redirect to desired activity or URL
    }
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        dialog.dismiss();
    }
});
AlertDialog dialog = builder.create();
dialog.show();

In this code, an alert dialog is created with a title and message. The dialog has two buttons, "Yes" and "No". If the user clicks "Yes", the app can redirect to the desired activity or URL. If the user clicks "No", the dialog is dismissed and nothing happens. You can customize the title, message, and button text to suit your needs.



Invoke an Alert Dialog with Confirm to Redirect After Scanning a QR Code in an iOS App

To invoke an alert dialog with confirm to redirect after scanning a QR Code in an iOS app, you can follow these steps.

1. Import the UIKit framework at the top of your Swift file.


import UIKit

Create a function to handle the alert dialog and redirect. Here's an example.


func showAlertAndRedirect(urlString: String) {
    let alert = UIAlertController(title: "QR Code Scanned", message: "Do you want to open the following URL?", preferredStyle: .alert)

    let yesAction = UIAlertAction(title: "Yes", style: .default) { action in
        if let url = URL(string: urlString) {
            UIApplication.shared.open(url)
        }
    }

    let noAction = UIAlertAction(title: "No", style: .cancel, handler: nil)

    alert.addAction(yesAction)
    alert.addAction(noAction)

    present(alert, animated: true, completion: nil)
}

Call the showAlertAndRedirect function after scanning the QR Code barcode and retrieving the URL. Here's an example.


if let url = URL(string: scannedUrlString) {
    showAlertAndRedirect(urlString: scannedUrlString)
}

This will display an alert dialog with a "Yes" and "No" button. If the user taps "Yes", the app will redirect to the scanned URL. If the user taps "No", the alert dialog will be dismissed and nothing will happen.



I Use ShowDialog in Side the Scaffold But I Didn't Get the Scanned Data of QR Code

I use ShowDialog in the function it need a context of Widget, so I used AlertDialog directly. I didn't get the scanned data of QR Code if I use ShowDialog in side the scaffold. So what should I do?

If you are not able to use showDialog method within a widget's context, you can use the showDialog method outside the widget tree by creating a new instance of BuildContext using the Builder widget. Here's an example code snippet that shows how you can use showDialog method outside the widget tree.


import 'package:flutter/material.dart';
import 'package:barcode_scan/barcode_scan.dart';
import 'package:flutter/services.dart';

class QRScannerScreen extends StatefulWidget {
  @override
  _QRScannerScreenState createState() => _QRScannerScreenState();
}

class _QRScannerScreenState extends State<QRScannerScreen> {
  String qrCodeData = "";

  Future<void> _scanQRCode() async {
    try {
      final result = await BarcodeScanner.scan();
      setState(() {
        qrCodeData = result.rawContent;
      });
      _showAlertDialog(context);
    } on PlatformException catch (e) {
      if (e.code == BarcodeScanner.cameraAccessDenied) {
        setState(() {
          qrCodeData = 'The user did not grant the camera permission!';
        });
      } else {
        setState(() {
          qrCodeData = 'Unknown error: $e';
        });
      }
    } on FormatException {
      setState(() {
        qrCodeData = 'null (User returned using the "back"-button before scanning anything. Result)';
      });
    } catch (e) {
      setState(() {
        qrCodeData = 'Unknown error: $e';
      });
    }
  }

  Future<void> _showAlertDialog(BuildContext context) async {
    return showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text("Confirm Navigation?"),
          content: Text("Do you want to navigate to the URL: $qrCodeData?"),
          actions: <Widget>[
            FlatButton(
              child: Text("Cancel"),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
            FlatButton(
              child: Text("OK"),
              onPressed: () {
                Navigator.of(context).pop();
                // Add your navigation code here
              },
            ),
          ],
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("QR Scanner"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text("Scanned Data: $qrCodeData"),
            SizedBox(height: 20),
            RaisedButton(
              onPressed: _scanQRCode,
              child: Text("Scan QR Code"),
            ),
          ],
        ),
      ),
    );
  }
}

In the above code, the _showAlertDialog method uses showDialog to display an AlertDialog with two buttons to confirm or cancel the navigation to the scanned URL. You can also customize the AlertDialog widget to your liking based on your app's design requirements.