flutter_ble_central 0.0.1 copy "flutter_ble_central: ^0.0.1" to clipboard
flutter_ble_central: ^0.0.1 copied to clipboard

outdated

A Flutter package for scanning BLE data in central mode.

example/lib/main.dart

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_ble_central/flutter_ble_central.dart';
import 'package:permission_handler/permission_handler.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final FlutterBleCentral bleCentral = FlutterBleCentral();

  late final Stream<String> scanResultStream;
  Map<String, ScanResult> devices = {};

  int i = 0;
  @override
  void initState() {
    super.initState();
    initPlatformState();
    bleCentral.onScanResult.listen((event) {
      i++;
      debugPrint(
        'FLUTTER $i rssi ${event.rssi} manudata ${event.scanRecord?.manufacturerSpecificData}',
      );
      if (event.device != null &&
          !devices.keys.contains(event.device?.address)) {
        setState(() {
          devices[event.device!.address] = event;
        });
      }
    });
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {
    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;
  }

  bool isScanning = false;

  Future<void> _requestPermissions() async {
    // await Permission.bluetooth.shouldShowRequestRationale;

    // if ()

    final Map<Permission, PermissionStatus> statuses = await [
      Permission.bluetooth,
      // Permission.bluetoothAdvertise,
      // Permission.bluetoothConnect,
      Permission.bluetoothScan,
      Permission.location,
    ].request();
    for (final status in statuses.keys) {
      if (statuses[status] == PermissionStatus.granted) {
        debugPrint('$status permission granted');
      } else if (statuses[status] == PermissionStatus.denied) {
        debugPrint(
          '$status denied. Show a dialog with a reason and again ask for the permission.',
        );
      } else if (statuses[status] == PermissionStatus.permanentlyDenied) {
        debugPrint(
          '$status permanently denied. Take the user to the settings page.',
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Flutter BLE Central example'),
          actions: <Widget>[
            IconButton(
              onPressed: _requestPermissions,
              icon: const Icon(Icons.security),
            ),
            if (isScanning)
              IconButton(
                icon: const Icon(Icons.pause_circle_filled),
                onPressed: () => setState(() {
                  isScanning = false;
                  bleCentral.stop();
                }),
              )
            else
              IconButton(
                icon: const Icon(Icons.play_arrow),
                onPressed: () {
                  setState(() {
                    isScanning = true;
                    devices.clear();
                    bleCentral.start();
                  });
                },
              )
          ],
        ),
        body: devices.isEmpty
            ? const Center(
                child: Text('No device'),
              )
            : ListView.separated(
                padding: const EdgeInsets.all(8),
                itemBuilder: (BuildContext context, int index) {
                  final scanResult = devices.values.elementAt(index);
                  return Card(
                    child: Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Row(
                        children: <Widget>[
                          const Icon(Icons.bluetooth),
                          Expanded(
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: <Widget>[
                                // Text(s),
                                Text('${scanResult.scanRecord?.deviceName}'),
                                Text('${scanResult.device?.address}'),
                                Text('RSSI: ${scanResult.rssi}'),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),
                  );
                },
                separatorBuilder: (context, index) => const SizedBox(height: 5),
                itemCount: devices.length,
              ),
      ),
    );
  }
}
1
likes
0
pub points
50%
popularity

Publisher

verified publishersteenbakker.dev

A Flutter package for scanning BLE data in central mode.

License

unknown (LICENSE)

Dependencies

flutter, json_annotation

More

Packages that depend on flutter_ble_central