Skip to content

Instantly share code, notes, and snippets.

@sbis04
Created March 4, 2019 17:14
Show Gist options
  • Save sbis04/e897fa2c17501e14b7f39aa1c9c51a95 to your computer and use it in GitHub Desktop.
Save sbis04/e897fa2c17501e14b7f39aa1c9c51a95 to your computer and use it in GitHub Desktop.
Bluetooth connection
class _BluetoothAppState extends State<BluetoothApp> {
...
@override
void initState() {
super.initState();
bluetoothConnectionState();
}
// We are using async callback for using await
Future<void> bluetoothConnectionState() async {
List<BluetoothDevice> devices = [];
// To get the list of paired devices
try {
devices = await bluetooth.getBondedDevices();
} on PlatformException {
print("Error");
}
// For knowing when bluetooth is connected and when disconnected
bluetooth.onStateChanged().listen((state) {
switch (state) {
case FlutterBluetoothSerial.CONNECTED:
setState(() {
_connected = true;
_pressed = false;
});
break;
case FlutterBluetoothSerial.DISCONNECTED:
setState(() {
_connected = false;
_pressed = false;
});
break;
default:
print(state);
break;
}
});
// It is an error to call [setState] unless [mounted] is true.
if (!mounted) {
return;
}
// Store the [devices] list in the [_devicesList] for accessing
// the list outside this class
setState(() {
_devicesList = devices;
});
}
@override
Widget build(BuildContext context) {
return Container(
// We have to work on the UI in this part
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment