dart Flutter StreamSubscription与listen一起使用,但不能在StreamBuilder小部件中使用

0ejtzxu1  于 2023-07-31  发布在  Flutter
关注(0)|答案(1)|浏览(144)

当然!这里是在Stack Overflow上寻求帮助的固定消息:
我正在使用flutter_blue_plusflutter_foreground_task包。
我有一个名为BluetoothTaskHandler的蓝牙处理程序类,它扩展了TaskHandler。代码如下:

class BluetoothTaskHandler extends TaskHandler {
  SendPort? _sendPort;

  @override
  Future<void> onStart(DateTime timestamp, SendPort? sendPort) async {
    _sendPort = sendPort;
    // Here, I perform the setup for the Bluetooth device, services, characteristics, and listeners.
  }

  // This is the listener specific to a characteristic.
  void onBreathEcgValueReceived(List<int> event) {
    // Send data to the main isolate.
    EcgBrtValueDto? result = bluetoothBreathEcgInterpreter.getEcgBrt(Uint8List.fromList(event));
    if (result != null) {
      var brt = result.brt;
      var ecg = result.ecg;

      logger.info("@onBreathEcgValueReceived ecg ${ecg.toString()}");
      logger.info("@onBreathEcgValueReceived brt ${brt.toString()}");

      if (_sendPort != null) {
        FlutterForegroundTask.isAppOnForeground.then((isAppOnForeground) {
          if (isAppOnForeground) {
            _sendPort?.send(json.encode(result.toJson()));
          }
        });
      }
    }
  }
}

字符串
在我的小部件中,我有以下代码(只有State部分是相关的)。有一条重要的评论:

@override
void initState() {
  super.initState();
  WidgetsBinding.instance.addPostFrameCallback((_) async {
    if (await FlutterForegroundTask.isRunningService) {
      setUpPortStream();
    }
  });

  WidgetsBinding.instance.addObserver(this);
}

setUpPortStream() {
  // Type: ReceivePort?
  final newReceivePort = FlutterForegroundTask.receivePort;
  if (newReceivePort == null) {
    logger.warn("@setUpPortStream no receive port");
    return;
  }

  /*** IMPORTANT: if I uncomment this, I see the data coming ***/
  /*newReceivePort.listen((message) {
    logger.info("Received $message");
  });*/

  return;

  // [..] Build stuff [..]

  StreamBuilder<dynamic>(
    // Already tried: stream: newReceivePort.asBroadcastStream(),
    stream: newReceivePort.asBroadcastStream(),
    builder: (context, snapshot) {
      List<Widget> children;
      if (!snapshot.hasData) {
        logger.debug("@showBatteryStatus snapshot has no data in it.");
        children = <Widget>[const Text('no data.')];
      }
      // [...]
    }
  );
}


我面临的问题是,它总是显示“无数据”在StreamBuilder。我还尝试使用convertSubscriptionToStream方法将订阅转换为流,但没有成功。
此外,在初始化前台任务之后,这是顶级回调:

// The callback function should always be a top-level function.
@pragma('vm:entry-point')
void startCallback() {
  // The setTaskHandler function must be called to handle the task in the background.
  FlutterForegroundTask.setTaskHandler(BluetoothTaskHandler());
}


我将感谢任何帮助或建议,为什么我没有在StreamBuilder接收数据。谢谢你,谢谢

wqsoz72f

wqsoz72f1#

停止将流创建为流:StreamBuilder的参数。看看为什么以及如何修复:https://youtu.be/sqE-J8YJnpg

相关问题