import 'package:flutter_bluetooth_serial/flutter_bluetooth_serial.dart';
class Light extends StatefulWidget {
final connection;
Light(this.connection);
@override
LightState createState() => LightState(connection);
}
class LightState extends State<Light> {
final BluetoothConnection connection;
var controller = BehaviorSubject();
LightState(this.connection);
double depth = 10;
int lightValue = 580;
Color color = Colors.white54;
Color currentColor = Colors.limeAccent;
void changeColor(Color color) => setState(() => currentColor = color);
@override
void initState() {
super.initState();
if (connection != null) {
if (!connection.input.isBroadcast) {
var listen = connection.input.asBroadcastStream();
listen.listen((data) {
setState(() {
lightValue = data[0];
});
print(lightValue);
});
}
}
}
@override
void dispose() async {
super.dispose();
await connection.close();
connection.dispose();
}
@override
Widget build(BuildContext context) {
final size = 200.0;
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: Text("Light"),
backgroundColor: Colors.black,
),
body: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [
Color(0xff323232),
Color(0xff050505),
],
)),
child: Stack(
children: [
Center(
child: Container(
width: size,
height: size,
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(100)),
boxShadow: [
BoxShadow(
offset: Offset(1, 1),
color: color,
blurRadius: 50,
spreadRadius: 1,
),
]),
child: Stack(
children: [
ShaderMask(
shaderCallback: (rect) {
return LinearGradient(
transform: GradientRotation(-1.5708),
stops: [lightValue / 255, 0],
colors: [Color(0xff010e80), Colors.transparent])
.createShader(rect);
},
child: Container(
width: size,
height: size,
decoration: BoxDecoration(
shape: BoxShape.circle, color: Colors.white),
),
),
],
),
),
),
),
],
),
);
}
}
当您以这种方式连接到蓝牙时,连接是在另一个小部件中定义的:
await BluetoothConnection.toAddress(_device.address)
.then((_connection) {
print('Connected to the device');
connection = _connection;
setState(() {
_connected = true;
});
然后此连接通过构造函数发送到 Light StatefulWidget。
该小部件在单击时打开,在我离开并再次打开它后给出 Bad State: Stream has already been listened to.
。
我已经尝试使用 StreamBuilder 但它给出了同样的错误。
我已经查看了相关问题,有人指出使用广播或 BehaviorSubject。但是我找不到将它们与 bluetooth_serial 包一起使用的方法。