when I use build version as in flutter run it's able to connect to the bluetooth device but when I build the app and install it it won't connect to the bluetooth device?


import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'package:flutter/material.dart';
import 'package:just_audio/just_audio.dart';
import 'package:flutter_blue/flutter_blue.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:flutter_blue/gen/flutterblue.pb.dart' as ProtoBluetoothDevice;
import 'package:http/http.dart' as http;

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(
    MaterialApp(
      theme: ThemeData.dark(),
      home: TakePictureScreen(
        takePictureScreenState: TakePictureScreenState(),
      ),
    ),
  );
}

class TakePictureScreen extends StatefulWidget {
  final TakePictureScreenState takePictureScreenState;

  const TakePictureScreen({
    Key? key,
    required this.takePictureScreenState,
  }) : super(key: key);

  @override
  TakePictureScreenState createState() => takePictureScreenState;
}

class TakePictureScreenState extends State<TakePictureScreen>
    with ChangeNotifier {
  FlutterBlue flutterBlue = FlutterBlue.instance;
  BluetoothDevice? targetDevice;
  BluetoothCharacteristic? targetCharacteristic;
  String direction = "In";
  StreamSubscription<BluetoothDeviceState>? connectionStateSubscription;
  bool isConnecting = false;

  @override
  void initState() {
    super.initState();
    requestBluetoothPermissions();

    // To display the current output from the Camera,
    // create a CameraController.

    // Next, initialize the controller. This returns a Future.
  }

Future<void> requestBluetoothPermissions() async {
  if (Platform.isAndroid) {
    final statuses = await [
      Permission.bluetooth,
      Permission.bluetoothConnect,
      Permission.bluetoothScan,
      Permission.bluetoothAdvertise,
      Permission.location,
    ].request();

    // Check the permissions statuses here, handle them accordingly, for example:
    final bluetoothGranted = statuses[Permission.bluetooth]?.isGranted ?? false;
    if (!bluetoothGranted) {
      // Handle a situation when Bluetooth permissions are not granted
    }
  }
}

  void setDirection(String direction) {
    this.direction = direction;
    notifyListeners();
  }

  bool canPop(BuildContext context) {
    return Navigator.of(context).canPop();
  }

  void connectToDevice(BuildContext context, String macAddress) async {
    if (isConnecting) {
      return;
    }

    isConnecting = true;
    var protoBt = ProtoBluetoothDevice.BluetoothDevice(remoteId: macAddress);
    var d = BluetoothDevice.fromProto(protoBt);
    targetDevice = d;

    targetDevice!.connect().then((_) {
      handleBluetoothDevice().then((_) {
        isConnecting = false;
        Navigator.push(
          context,
          MaterialPageRoute(
              builder: (context) =>
                  BluetoothScreen(takePictureScreenState: this)),
        );
      }).catchError((error) {
        if (canPop(context)) {
          Navigator.pop(context);
        }
      });
    }).catchError((error) {
      if (canPop(context)) {
        Navigator.pop(context);
      }
    });

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

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

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

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

  Future<void> captureAndSendImage(String numberString) async {
    // Your existing code here...
    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) {
    }
  }



  @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";

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Bluetooth Screen'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            RadioListTile<String>(
              title: const Text('Invägning'),
              value: 'In',
              groupValue: direction,
              onChanged: (String? value) {
                setState(() {
                  direction = value!;
                });
                widget.takePictureScreenState.setDirection(direction);
              },
            ),
            RadioListTile<String>(
              title: const Text('Utvägning'),
              value: 'Out',
              groupValue: direction,
              onChanged: (String? value) {
                setState(() {
                  direction = value!;
                });
                widget.takePictureScreenState.setDirection(direction);
              },
            ),
            Padding(
  padding: const EdgeInsets.only(top: 200.0), // Adjust the value for desired distance
  child: ElevatedButton(
              onPressed: () => _showManualWeightDialog(),
              child: const Text("Manuell"),
                  style: ElevatedButton.styleFrom(
      padding: const EdgeInsets.symmetric(horizontal: 125, vertical: 20), // Adjust for size
      textStyle: const TextStyle(
        fontSize: 16, // Adjust font size if needed
      ),
                  ),
            ),
            ),
          ],
        ),
      ),
    );
  }
  Future<void> _showManualWeightDialog() async {
  // Controller to handle text input
  TextEditingController weightController = TextEditingController();

  return showDialog<void>(
    context: context,
    barrierDismissible: false, // user must tap button to close dialog
    builder: (BuildContext context) {
      return AlertDialog(
        title: Text("Skriv in vikt"),
        content: SingleChildScrollView(
          child: ListBody(
            children: <Widget>[
              TextField(
                controller: weightController,
                decoration: InputDecoration(
                  hintText: "Skriv in vikten du vill lägga in",
                ),
                keyboardType: TextInputType.numberWithOptions(decimal: true), // To allow decimal input
              ),
            ],
          ),
        ),
        actions: <Widget>[
          TextButton(
            child: const Text("Avbryt"),
            onPressed: () => Navigator.of(context).pop(),
          ),
          TextButton(
            child: const Text("Yes box"),
            onPressed: () {
            String enteredWeight = weightController.text;
                // Use the instance to call the method, assuming widget.takePictureScreenState is your instance.
              widget.takePictureScreenState.captureAndSendImage(enteredWeight);
              Navigator.of(context).pop();
            },
          ),
        ],
      );
    },
  );
}
}




class BluetoothScreen extends StatefulWidget {
  final TakePictureScreenState takePictureScreenState;

  const BluetoothScreen({
    Key? key,
    required this.takePictureScreenState,
  }) : super(key: key);

  @override
  _BluetoothScreenState createState() => _BluetoothScreenState();
}