1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
|
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:logger/logger.dart';
var logger = Logger(printer: PrettyPrinter());
class DeviceDetailsScreen extends StatefulWidget {
final BluetoothDevice btDevice;
const DeviceDetailsScreen({super.key, required this.btDevice});
@override
State<StatefulWidget> createState() {
return DeviceDetailsState();
}
}
class DeviceDetailsState extends State<DeviceDetailsScreen> {
String connectStatus = "<Status>";
// Just to have a resonable default subscription?
StreamSubscription<BluetoothConnectionState> subs =
Stream<BluetoothConnectionState>.empty().listen((e) => ());
/// Whether the back button should be active.
bool backActive = false;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: Text("Device details"),
),
body: Center(
child: Column(
spacing: 20,
children: [
Text(connectStatus),
ElevatedButton(
onPressed: backActive ? backClick : null,
child: Text("Back"),
),
],
),
),
);
}
@override
void initState() {
super.initState();
_doConnect();
}
void backClick() {
Navigator.pop(context);
}
void onConnStateChange(BluetoothConnectionState event) {
setState(() {
connectStatus = event.toString();
});
logger.i("New conn state: ${event.toString()}");
}
@override
void deactivate() {
super.deactivate();
logger.i("Closing state");
subs.cancel().ignore();
widget.btDevice.disconnect().ignore();
}
void _doConnect() async {
final dev = widget.btDevice;
subs.cancel().ignore();
subs = dev.connectionState.listen(onConnStateChange);
try {
logger.i("Try to connect...");
// connect timeout doesn't work under Linux
await dev.connect().timeout(Duration(seconds: 2));
logger.i("Connected!");
connectStatus = "Connected";
} catch (e) {
logger.e(e);
dev.disconnect().ignore();
connectStatus = e.toString();
} finally {
backActive = true;
if (mounted) {
setState(() {});
}
}
}
}
|