美文网首页Flutter
flutter isolate 主和子相互交流

flutter isolate 主和子相互交流

作者: 代瑶 | 来源:发表于2021-06-19 21:16 被阅读0次
    library flutter_flutterisolate2;
    
    import 'dart:async';
    import 'dart:isolate';
    
    ///
    /// Isolate 默认是主的, 在主Isolate中启动的子Isolate需要交互需要用到SendPort
    main() async {
      ///沟通需要的接收port
      ReceivePort childReceiveMainPort = new ReceivePort();
    
      ///创建一个子Isolate,得到子Isolate的接收器和发送器
      await Isolate.spawn<SendPort>(_isolateChildFunction, childReceiveMainPort.sendPort);
      SendPort fromChildSendPort = await childReceiveMainPort.first;
    
      ReceivePort _chatReceivePort = ReceivePort();
      fromChildSendPort.send(["洞拐", _chatReceivePort.sendPort]);
      String receiveMessage = await _chatReceivePort.first;
      print('receiveMessage  $receiveMessage');
    }
    
    ///需要交互的子函数
    _isolateChildFunction(SendPort fromMainSendPort) async {
      ReceivePort childReceivePort = new ReceivePort();
      fromMainSendPort.send(childReceivePort.sendPort);
    
      dynamic _fromMainMessage = await childReceivePort.first;
      String _mainMessage = _fromMainMessage[0];
      SendPort _fromMainSendPort = _fromMainMessage[1];
      _fromMainSendPort.send("洞妖洞妖我是:" + _mainMessage);
    }
    
    
    image.png
    library flutter_flutterisolate2;
    
    import 'dart:async';
    import 'dart:isolate';
    
    ///
    /// Isolate 默认是主的, 在主Isolate中启动的子Isolate需要交互需要用到SendPort
    main() async {
      ///沟通需要的接收port
      ReceivePort childReceiveMainPort = new ReceivePort();
    
      ///创建一个子Isolate,得到子Isolate的接收器和发送器
      await Isolate.spawn<SendPort>(_isolateChildFunction, childReceiveMainPort.sendPort);
      childReceiveMainPort.listen((message) {
        dynamic _msgObj = message;
        int _index = _msgObj[0];
        if (_index == 0) {
          SendPort fromChildSendPort = _msgObj[1];
          fromChildSendPort.send("洞拐");
        } else if (_index == 1) {
          print('receiveMessage  ${_msgObj[1]}');
        }
      });
    }
    
    ///需要交互的子函数
    _isolateChildFunction(SendPort fromMainSendPort) async {
      ReceivePort childReceivePort = new ReceivePort();
      fromMainSendPort.send([0, childReceivePort.sendPort]);
    
      dynamic _fromMainMessage = await childReceivePort.first;
      String _mainMessage = _fromMainMessage;
      fromMainSendPort.send([1, "洞妖洞妖我是:" + _mainMessage]);
    }
    
    

    不需要多次创建ReceivePort

    image.png

    相关文章

      网友评论

        本文标题:flutter isolate 主和子相互交流

        本文链接:https://www.haomeiwen.com/subject/drvdyltx.html