// // flutter bluetooth notify with stream example // // change android/app/build.gradle // line 42 minSDKVersion to at least 19 // // pubspec yaml: flutter_ble_lib: ^2.2.4 // // make sure bluetooth and location is turned on // on the phone/tablet // // also if you're having problem // goto phone settings // find this app // allow permission for location // import 'package:flutter/material.dart'; import 'dart:typed_data'; import 'package:flutter_ble_lib/flutter_ble_lib.dart'; void main() {runApp(MyApp());} class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp(title: 'Flutter Demo', home: Home());}} class Home extends StatefulWidget { Home({Key key, this.title}) : super(key: key); final String title; @override _HomeState createState() => _HomeState();} class _HomeState extends State { BleManager ble = BleManager(); Peripheral peri; List servs; Service serv; List chars; Characteristic char; Stream stream; String data = "init data"; connectToBle() async { await ble.createClient(); print("************************connecttoble func"); ble.startPeripheralScan() .listen((scanResult) async { print("*******************scanresult"); if (scanResult.peripheral.name == "Adafruit Bluefruit LE") { print("**************found adafruit"); peri = scanResult.peripheral; ble.stopPeripheralScan(); //await peri.disconnectOrCancelConnection(); bool c = await peri.isConnected(); if (!c) { await peri.connect(); await peri.isConnected();} //test if connected otherwise getting error connected already print("*****************connected"); await peri.discoverAllServicesAndCharacteristics(); servs = await peri.services(); serv = servs.singleWhere((s) => s.uuid == "6e400001-b5a3-f393-e0a9-e50e24dcca9e"); char = (await serv.characteristics()).singleWhere((c) => c.uuid == "6e400003-b5a3-f393-e0a9-e50e24dcca9e"); } }); } Stream startNotify(){ stream = char.monitor().asBroadcastStream(); return stream; } listen() { startNotify().listen((d){ setState((){ data = String.fromCharCodes(d); }); }); } @override void initState() { super.initState(); connectToBle(); } @override Widget build(BuildContext context){ return Scaffold( body: Column(children:[ SizedBox(height: 100), Text("data received: $data"), RaisedButton( onPressed:() => listen(), child: Text('connect'), ), ]), ); }}