#flutter
Вопрос:
У меня есть следующий код, и я не мог понять, в чем проблема. Я хочу передать устройство Bluetooth в контейнер в классе DeviceData, и этот класс возвращает контейнер. Я новичок в Flutter и, когда я прочитал документацию, не смог понять, о чем они говорят.
Но первая проблема заключается в
Не удается определить конструктор «const», поскольку поле «верхний раздел» инициализируется непостоянным значением. Попробуйте инициализировать поле постоянным значением или удалить ключевое слово «const» из
и тогда доступ к устройству будет невозможен:
Элемент экземпляра «устройство» не может быть доступен в инициализаторе. Попробуйте заменить ссылку на элемент экземпляра другим выражением
class DeviceData extends StatelessWidget {
const DeviceData({Key key, this.device}) : super(key: key);
final BluetoothDevice device;
final uppersection = new Container(
child: Row(
children: <Widget>[
StreamBuilder<BluetoothDeviceState>(
stream: device.state,
initialData: BluetoothDeviceState.connecting,
builder: (c, snapshot) => ListTile(
leading: (snapshot.data == BluetoothDeviceState.connected)
? Icon(Icons.bluetooth_connected)
: Icon(Icons.bluetooth_disabled),
title: Text('Device is ${snapshot.data.toString().split('.')[0]}.'),
subtitle: Text('${device.id}'),
trailing: StreamBuilder<bool>(
//The below stream is to show either a refresh button or
//CircularProgress based on the service discovering status,
//and a IndexedStack widget is used to present the needed widget
stream: device.isDiscoveringServices,
initialData: false,
builder: (c, snapshot) => IndexedStack(
index: snapshot.data ? 0 : 0,
children: <Widget>[
IconButton(
icon: Icon(Icons.refresh),
onPressed: () => device.discoverServices(),
),
IconButton(
icon: SizedBox(
child: CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation(Colors.grey),
),
width: 17.0,
height: 17.0,
),
onPressed: null,
),
],
),
),
),
),
],
),
);
@override
Widget build(BuildContext context) {
return new Container(
child: Column(
children: <Widget>[
uppersection,
],
),
);
}
}
Ответ №1:
Тебе лучше стать upperSection
добытчиком.
Вот так:
Container get upperSection{
return Container(
child: Row(
children: <Widget>[
StreamBuilder<BluetoothDeviceState>(
stream: device.state,
initialData: BluetoothDeviceState.connecting,
builder: (c, snapshot) => ListTile(
leading: (snapshot.data == BluetoothDeviceState.connected)
? Icon(Icons.bluetooth_connected)
: Icon(Icons.bluetooth_disabled),
title: Text('Device is ${snapshot.data.toString().split('.')[0]}.'),
subtitle: Text('${device.id}'),
trailing: StreamBuilder<bool>(
//The below stream is to show either a refresh button or
//CircularProgress based on the service discovering status,
//and a IndexedStack widget is used to present the needed widget
stream: device.isDiscoveringServices,
initialData: false,
builder: (c, snapshot) => IndexedStack(
index: snapshot.data ? 0 : 0,
children: <Widget>[
IconButton(
icon: Icon(Icons.refresh),
onPressed: () => device.discoverServices(),
),
IconButton(
icon: SizedBox(
child: CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation(Colors.grey),
),
width: 17.0,
height: 17.0,
),
onPressed: null,
),
],
),
),
),
),
],
),
);
}