flutter_ble_reader 0.0.1 flutter_ble_reader: ^0.0.1 copied to clipboard
Based on ble
example/lib/main.dart
import 'package:flutter/material.dart';
import 'package:flutter_plugin/flutter_blue.dart';
import 'package:flutter_plugin/scan_result_model.dart';
import 'package:flutter_plugin/scanning_device.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: FlutterBlueApp(homeScreenWidget: const ScanScreen(),),
);
}
}
class ScanScreen extends StatefulWidget {
const ScanScreen({Key? key}) : super(key: key);
@override
State<ScanScreen> createState() => _ScanScreenState();
}
class _ScanScreenState extends State<ScanScreen> {
final FlutterBluePlugin _bluetoothPlugin = FlutterBluePlugin();
List<ScanResultModel> _scanResults = [];
bool _isScanning = false;
@override
void initState() {
super.initState();
_bluetoothPlugin.scanResults.listen((results) {
setState(() {
_scanResults = results;
});
});
_bluetoothPlugin.isScanning.listen((state) {
setState(() {
_isScanning = state;
});
});
startScan();
}
Future<void> startScan() async {
await _bluetoothPlugin.startScan();
Future.delayed(const Duration(seconds: 5), () async {
await stopScan();
});
}
Future<void> stopScan() async {
await _bluetoothPlugin.stopScan();
}
@override
void dispose() {
_bluetoothPlugin.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text("Bluetooth Scan")),
body: Column(
children: [
Text(_isScanning ? "Scanning..." : "Scan Stopped"),
Expanded(
child: ListView.builder(
itemCount: _scanResults.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(_scanResults[index].device.name),
subtitle: Text(_scanResults[index].device.id.toString()),
);
},
),
),
ElevatedButton(
onPressed: _isScanning ? stopScan : startScan,
child: Text(_isScanning ? "Stop Scan" : "Start Scan"),
),
],
),
);
}
}