如何在流更改状态时更新我的​​ get 函数?

How can I update my get function when stream changes state?

我正在使用 flutter_blue_plus 打开或关闭蓝牙。我在日志中成功获得了结果。但是在 isOn 函数中,我无法自动更新。我能做什么?我必须在 UI 中使用 StreamBuilder 吗?

class BluetoothService with Logger {
  BluetoothService() {
    log.fine('listening to bluetooth status changes');

    FlutterBluePlus.instance.state.listen((result) {
      log.fine('bluetooth state changed to ${result.name}');
      _lastResult = result;
    });
  }
  BluetoothState _lastResult = BluetoothState.unknown;

  /// The last [BluetoothState] that is updated automatically whenever the
  /// state changes.

  bool get isOn => _lastResult == BluetoothState.on;

  Future<void> initialize() async {
    try {
      await FlutterBluePlus.instance.isAvailable;
    } catch (e, st) {
      log.warning('unable to initialize bluetooth', e, st);
    }
  }
}
        

class BluetoothDeviceList extends StatelessWidget {
  const BluetoothDeviceList({Key? key}) : super(key: key);
  static const route = 'bluetoothdevicelist';

  @override
  Widget build(BuildContext context) {
    return app<BluetoothService>().isOn
        ? Scaffold(
            body: Center(child: Text('DEVICES')),
          )
        : Scaffold(
            body: Center(child: Text('Bluetooth Close')),
          );
  }
}

这绝对是您需要使用一些 state management approach. In our team we use flutter_bloc 的情况,在这种情况下,您的解决方案将如下所示。

class BluetoothCubit extends Cubit<BluetoothState> with Logger {
  BluetoothCubit() : super(BluetoothState.unknown) {
    log.fine('listening to bluetooth status changes');

    FlutterBluePlus.instance.state.listen((result) {
      log.fine('bluetooth state changed to ${result.name}');
      emit(result);
    });
  }

  Future<void> initialize() async {
    try {
      await FlutterBluePlus.instance.isAvailable;
    } catch (e, st) {
      log.warning('unable to initialize bluetooth', e, st);
    }
  }
}

class BluetoothDeviceList extends StatelessWidget {
  static const route = 'bluetoothdevicelist';

  const BluetoothDeviceList({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) => BlocProvider(
        create: (_) => BluetoothCubit()..initialize(),
        child: BlocBuilder<BluetoothCubit, BluetoothState>(
          builder: (context, state) => Scaffold(
            body: Center(
              child: Text(
                state == BluetoothState.on ? 'DEVICES' : 'Bluetooth Close',
              ),
            ),
          ),
        ),
      );
}

其中一个关键变化是在您的流监听器中调用 emit(result)。这会通知 BlocBuilder 需要显示新状态。

还有其他方法可以处理这个问题,但这是我们公司的标准方法。