I know BT devices are classic and BLE type in my case i am trying to connect with a classic type which is a HOIN mobile thermal printer with bt version 2.0 for android and V4.0 for ios and it also has USB support, so my device is classic type.

here i am using FlutterBlue package and permissionHandler package, i make an instance of flutterBlue thenuser it to scan, listen for changes and then list them using a stream but unfortunately its not showing any nearby devices ive tried everything, i put permissions in manifest file which are:

<uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.USB_DEVICE" />

    <uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>
    <uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
    <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
    <!-- <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> -->
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <!-- <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" /> -->

and i am making all necessary checks for checking if permissions are granted by user and if not ask for them and all this works fine, i even listen to the bt adapter state if it is on or off but still something is going wrong and i am unable to resolve the issue.

here is my code to scan and list devices:


import 'dart:developer';

import 'package:flutter/material.dart';
import 'package:flutter_blue/flutter_blue.dart';
import 'package:lottery/widgets/snackbar_widget.dart';
import 'package:permission_handler/permission_handler.dart';

class FBScreen extends StatefulWidget {
  const FBScreen({super.key});

  @override
  State<FBScreen> createState() => _FBScreenState();
}

class _FBScreenState extends State<FBScreen> {
  FlutterBlue flutterBlue = FlutterBlue.instance;

  showAlert(String rTitle, String rBody) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return PopupWidget(
          title: rTitle,
          body: rBody,
        );
      },
    );
  }

  void _connectToDevice(BluetoothDevice device) async {
    try {
      await device.connect();
      setState(() {
        connectedDevice = device;
      });
      //returning the connected device on pop so that print command can be sent
      Navigator.pop(context, connectedDevice);
    } catch (e, stackTrace) {
      log('Exception occurred, permissions are required: $e\n$stackTrace');
      showAlert(
          "Exception occurred", "when connecting to device: $e\n$stackTrace");
    }
  }

  Future scanDevices() async {
    var blePermission = await Permission.bluetooth.status;
    var bleConperm = await Permission.bluetoothConnect.status;
    var bleScanperm = await Permission.bluetoothScan.status;
    log("bluetooth status: $blePermission, bluetooth connect status: $bleConperm, scanning permission: $bleScanperm");

    showCustomSnackbar(context, "Success",
        "bluetooth status: $blePermission, bluetooth connect status: $bleConperm, scanning permission: $bleScanperm");

    if (blePermission.isDenied) {
      log("in req permission case");
      if (await Permission.bluetoothScan.request().isGranted) {
        if (await Permission.bluetoothConnect.request().isGranted) {
          flutterBlue.startScan();
          await Future.delayed(const Duration(seconds: 10));
          flutterBlue.stopScan();
        }
      }
    } else {
      // if permissions are granted
      log("in granted permission case");
      flutterBlue.startScan();
      await Future.delayed(const Duration(seconds: 10));
      flutterBlue.stopScan();
      showCustomSnackbar(context, "Success", "${getScanResults.toString()}");
    }
  }

  Stream<List<ScanResult>> get getScanResults => flutterBlue.scanResults;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("BLE eg"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const SizedBox(
              height: 15,
            ),
            StreamBuilder<List<ScanResult>>(
                stream: getScanResults,
                builder: (context, snapshot) {
                  if (snapshot.hasData) {
                    // Access the scan results from the snapshot.data
                    List<ScanResult> scanResults = snapshot.data!;

                    return ListView.builder(
                      shrinkWrap: true,
                      itemCount: scanResults.length,
                      itemBuilder: (context, index) {
                        final data = scanResults[index];
                        return Card(
                          elevation: 2,
                          child: ListTile(
                            onTap: () {
                              //connect to the device
                              _connectToDevice(data.device);
                            },
                            title: Text(data.device.name),
                            subtitle: Text(data.device.id.id),
                            trailing: Text(data.rssi.toString()),
                          ),
                        );
                      },
                    );
                  } else {
                    return const Center(
                      child: Text("No Device Found"),
                    );
                  }
                }),
            ElevatedButton(
                onPressed: () => scanDevices(), child: const Text("Scan")),
            const SizedBox(
              height: 15,
            ),
          ],
        ),
      ),
    );
  }
}

above code returns the connected device on pop so that print command can be sent from the home page and disconnect button is on homepage so user can stay connected as long as needed. NOTE: the thermal printer also has a password which is 0000 so idk how to provide password when connecting to it as the package has no password param where i could provide it. but this is a later stage issue since no devices are showing on scan. (logs are clean, no errors or warnings)

i also tried to print using usb cabel for which i had used serial_usb package but that also did not work.

can you please try this code in your system and see why devices are not showing and tell me how to resolve the issue of scanning,listing and connecting to device.

if all else fails than a working version of code with usb mode if possible.

I tried to scan, list and connect to the nearby BT devices using FlutterBlue package but the devices are not getting detected and not getting listed on the screen I have both type of devices on standby to be detected in the scanning process but no luck.

I tried to print to the thermal printer using a app from playstore called rawbt and it is showing the device and printing all data sucessfully (its even printing an image) its showing all type of device ie: classic and ble so i dont know why its not working in flutter.

Please help me resolve this issue i cant seem to understand what mistake i am making.

0

There are 0 answers