When it comes to using Bluetooth along with flutter, there is close to no documentation available. Whatever few articles are available, they are either too technical to bog you down, or are not clearly explained and become overwhelming. We will help you by demonstrating some basic concepts to implement Bluetooth functionality with flutter in your app.
We will be using the “flutter Bluetooth serial” plugin in the app to add Bluetooth. This plugin is implemented from another parent plugin called “flutter blue”. Although it is a new plugin and is not entirely bug-free but minds you it will definitely do your job.
Note: Before moving forward it would be important for you to know that this plugin will work only for android devices.
Bluetooth plugin for flutter can be easily used. Just follow these steps:
Firstly, add this dependency in your “pubspec.yaml” file:
The code of the app in the “main.dart” file will look like this:
Now we will create a StatefulWidget called the “BluetoothApp”. Then we will define some variables and a key in the _BluetoothAppStore. Along with this, we will also get an instance of FlutterBluetoothSerial in this class. This class will enable to control and retrieve Bluetooth information:
Now we will be implementing the critical portion of the app. We have to get the list of paired Bluetooth devices and check whether Bluetooth is connected. This will be done asynchronously. Then we will also have to create a list of Bluetooth devices to be shown in the UI later.
These operations must be done in a “future” method, which will be called in initState().
Now it is time to move on to the UI, which is the most pretty part of flutter. The code will be pretty long but it would mostly be easy to read if you are somewhat familiar to the Flutter widget. Post completing the UI, you will have to implement some methods.
Now it is time to implement some methods. First, we will start with the _getDeviceItems() method:
Now that we have dealt with the UI, it’s time to use 4 methods. We will be using the connect and disconnect methods for this example. Then we will be implementing a method to display a snackbar to the user when no Bluetooth devices are connected when the user tries to connect.
Now we are mostly finished. We are left with two methods, one for sending a message when to turn on the Bluetooth and the other foe switching it off.
After falling all these steps, Dart work required to make this work is now complete. But still now, when we run the app, it will crash:
To fix this, we are required to add the SDK into the AndroidManifest. Follow these steps after navigating to your project folder: android -> app -> src -> main -> AndroidManifest.xml
Add these 2 lines of code in your AndroidManifest.xml file:
If you want world-class flutter services then you can hire Flutter developers from India. Concetto labs have in-house flutter app developers which are available to make your dream projects a reality.