if you discconnect the bluetooth device then start it up again and connect to it it sends 2x requiest so and 3x if you do it again:


void connectToDevice(BuildContext context, String macAddress) async {
  if (isConnecting) return;
  
  try {
    print("Connecting to device…");
    isConnecting = true;
    
    targetDevice = BluetoothDevice(remoteId: DeviceIdentifier(macAddress));
    await targetDevice!.connect();
    
    await handleBluetoothDevice();
    print("Happening");
    isConnecting = false;

    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => BluetoothScreen(takePictureScreenState: this),
      ),
    );
    
  } catch (e) {
    print("Connection error: $e");
    isConnecting = false;
    
    if (canPop(context)) {
      Navigator.pop(context);
    }
  }

  connectionStateSubscription = targetDevice!.connectionState.listen(
    (BluetoothConnectionState state) {
      if (state == BluetoothConnectionState.disconnected && canPop(context)) {
        Navigator.pop(context);
      }
    },
  );
}

  Future<void> handleBluetoothDevice() async {
    if (targetDevice == null) return;

    List<BluetoothService> services = await targetDevice!.discoverServices(subscribeToServicesChanged: false);
    services.forEach((service) {
      service.characteristics.forEach((characteristic) {
        if (characteristic.uuid.toString() ==
            "06d1e5e7-79ad-4a71-8faa-373789f7d93c") {
          print(service);
          targetCharacteristic = characteristic;
          characteristic.setNotifyValue(true);
          print(characteristic);
          characteristic.lastValueStream.listen((value) {
            handleReceivedData(value);
            print("foundit");
          });
          print("Found it");
        }
      });
    });
  }

  void handleReceivedData(List<int> data) {
    String dataString = String.fromCharCodes(data);
    try {
      String numberString =
          RegExp(r'[0-9\.]+').firstMatch(dataString)!.group(0)!;
      print("We are now here");
      print(numberString);
      captureAndSendImage(numberString);
    } catch (e) {
    }
  }

  Future<void> captureAndSendImage(String numberString) async {
    // Your existing code here...
    print("Last check");
    try {
      if (!mounted) return;
      String sanitizedNumber = numberString.replaceAll(",", ".");
      // Send the image to the server
      var request = http.MultipartRequest(
          'POST',
          Uri.parse(
              'https://octopus-app-bpfg8.ondigitalocean.app/api/phone/camera'));
      request.fields['weight'] = sanitizedNumber;
      request.fields['direction'] = direction;
      var res = await request.send();
      var response = await http.Response.fromStream(res);

      if (response.statusCode == 200) {
        // If the server returns a 200 OK response, then proceed
        var responseData = jsonDecode(response.body);
        var audioBase64 = responseData[1]['audio'];

        // Decode the Base64 string to bytes
        var audioBytes = base64Decode(audioBase64);

        // Save the audio to a temporary file
        var directory = await getApplicationDocumentsDirectory();
        var audioPath = '${directory.path}/temp.mp3';
        var audioFile = File(audioPath);
        await audioFile.writeAsBytes(audioBytes);

        // Load the audio file
        var player = AudioPlayer();
        await player.setUrl(audioPath);

        // Play the audio file
        player.play();
      } else {
        // If the server returns an error response,
      }
    } catch (e) {
      print(e);
    }
  }



  @override
  void dispose() {
    // Dispose of the controller when the widget is disposed.
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("Connect to Device")),
      body: Center(
        // Wrap the connect button within the Center widget
        child: ElevatedButton(
          // Adjust the style if you want to change the appearance of the button
          style: ElevatedButton.styleFrom(
            // Example of styling the button
            padding: const EdgeInsets.symmetric(horizontal: 50, vertical: 20),
          ),
          // Provide an onPressed callback.
          onPressed: () {
            // Calls your connection method
            connectToDevice(context, "20:FA:BB:01:97:BE");
          },
          child: const Text("Connect"), // Set the button text
        ),
      ),
    );
  }
}
class _BluetoothScreenState extends State<BluetoothScreen> {
  String direction = "In";