Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connect 2 apps with bluetooth and transmit data flutter

So I am making an app where I need to transmit data from one app to another app (Preferrable using bluetooth). Ive looked into the bluetooth plugin but I cant seem to understand how to do a connection between 2 devices and transfer some strings. Can somebody help? Id prefer a solution through bluetooth but if there isn't, please suggest something else
I need to develop on android 7 API 24

I did some research, and it looks like the https://pub.dev/packages/flutter_bluetooth_serial package is good for this. But Im unable to get the chat system in test app working. Can somebody help me out with that?

like image 257
Siddharth Agrawal Avatar asked Dec 04 '21 08:12

Siddharth Agrawal


People also ask

Can you use Bluetooth with flutter?

FlutterBlue aims to offer the most from both platforms (iOS and Android). Using the FlutterBlue instance, you can scan for and connect to nearby devices (BluetoothDevice).


Video Answer


1 Answers

First of all, there is no easy way. You must learn at least some basics of Bluetooth protocol if you want to work with it successfully. Of course, don't waste time trying to implement Bluetooth from scratch. Use packages and you will learn everything while writing code, reading documentation and debugging.

I'm using Flutter Blue package. It works both with other phones and any auxiliary devices. Example in description works perfectly. Everything that goes on top should be custom to your app; therefore there is no need to look for other code snippets.

Working with Bluetooth may be harder because the hardware component is involved. In cases like that debugging complexity grows exponentially. Split the process into smaller parts and you will be okey: scanning, detection, address read, connection, and so on.

This is a general code snippet to scan available devices. If the device is detected- the name is represented.

class BleScan extends StatefulWidget {
  @override
  _BleScanState createState() => _BleScanState();
}

class _BleScanState extends State<BleScan> {
  BluetoothService service;
  int scanDuration = 10; // seconds

  @override
  void initState() {
    FlutterBlue.instance.startScan(timeout: Duration(seconds: scanDuration));
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        Container(
          alignment: Alignment.center,
          child: Text('Search again if not detected'),
        ),
        StreamBuilder<List<ScanResult>>(
          stream: FlutterBlue.instance.scanResults,
          initialData: [],
          builder: (c, snapshot) => Column(
            children: snapshot.data
                .where((t) => t.device.name.contains(serialNumberMap[chosenSerial])) //Filter by name
                .map(
                  (r) => Text(r.device.name),
                )
                .toList(),
          ),
        ),
        Spacer(),
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            StreamBuilder<bool>(
              stream: FlutterBlue.instance.isScanning,
              initialData: false,
              builder: (c, snapshot) {
                if (snapshot.data) {
                  return Container();
                } else {
                  return FloatingActionButton.extended(
                    icon: Icon(Icons.search),
                    label: Text('Search again'),
                    onPressed: () {
                      FlutterBlue.instance.startScan(timeout: Duration(seconds: scanDuration));
                    },
                  );
                }
              },
            ),
          ],
        ),
      ],
    );
  }
}

This snippet can be used to connect to the device, read services and characteristics. Take a note that characteristic is a location where data exchange is happening as documented everywhere.

widget.device.connect(timeout: const Duration(seconds: 5), autoConnect: false).then((a) {
  widget.device.discoverServices().then((value) {
    value.forEach((service) {
      //services are here
      service.characteristics.forEach((characteristic) {
        //characteristics
      });
    });
  });
});
like image 131
Aplamis Avatar answered Oct 20 '22 17:10

Aplamis