@@ -73,6 +73,13 @@ - (instancetype)initWithConnection:(NSNumber*)connection
7373 */
7474@interface FlutterEngine () <FlutterBinaryMessenger>
7575
76+ /* *
77+ * A mutable array that holds one bool value that determines if responses to platform messages are
78+ * clear to execute. This value should be read or written only inside of a synchronized block and
79+ * will return `NO` after the FlutterEngine has been dealloc'd.
80+ */
81+ @property (nonatomic , strong ) NSMutableArray <NSNumber*>* isResponseValid;
82+
7683/* *
7784 * Sends the list of user-preferred locales to the Flutter engine.
7885 */
@@ -242,6 +249,8 @@ - (instancetype)initWithName:(NSString*)labelPrefix
242249 _allowHeadlessExecution = allowHeadlessExecution;
243250 _semanticsEnabled = NO ;
244251 _viewProvider = [[FlutterViewEngineProvider alloc ] initWithEngine: self ];
252+ _isResponseValid = [[NSMutableArray alloc ] initWithCapacity: 1 ];
253+ [_isResponseValid addObject: @YES ];
245254
246255 _embedderAPI.struct_size = sizeof (FlutterEngineProcTable);
247256 FlutterEngineGetProcAddresses (&_embedderAPI);
@@ -262,6 +271,10 @@ - (instancetype)initWithName:(NSString*)labelPrefix
262271}
263272
264273- (void )dealloc {
274+ @synchronized (_isResponseValid) {
275+ [_isResponseValid removeAllObjects ];
276+ [_isResponseValid addObject: @NO ];
277+ }
265278 [self shutDownEngine ];
266279 if (_aotData) {
267280 _embedderAPI.CollectAOTData (_aotData);
@@ -639,17 +652,25 @@ - (void)engineCallbackOnPlatformMessage:(const FlutterPlatformMessage*)message {
639652 }
640653 NSString * channel = @(message->channel );
641654 __block const FlutterPlatformMessageResponseHandle* responseHandle = message->response_handle ;
642-
655+ __block FlutterEngine* weakSelf = self;
656+ NSMutableArray * isResponseValid = self.isResponseValid ;
657+ FlutterEngineSendPlatformMessageResponseFnPtr sendPlatformMessageResponse =
658+ _embedderAPI.SendPlatformMessageResponse ;
643659 FlutterBinaryReply binaryResponseHandler = ^(NSData * response) {
644- if (responseHandle) {
645- _embedderAPI.SendPlatformMessageResponse (self->_engine , responseHandle,
646- static_cast <const uint8_t *>(response.bytes ),
647- response.length );
648- responseHandle = NULL ;
649- } else {
650- NSLog (@" Error: Message responses can be sent only once. Ignoring duplicate response "
651- " on channel '%@ '." ,
652- channel);
660+ @synchronized (isResponseValid) {
661+ if (![isResponseValid[0 ] boolValue ]) {
662+ // Ignore, engine was killed.
663+ return ;
664+ }
665+ if (responseHandle) {
666+ sendPlatformMessageResponse (weakSelf->_engine , responseHandle,
667+ static_cast <const uint8_t *>(response.bytes ), response.length );
668+ responseHandle = NULL ;
669+ } else {
670+ NSLog (@" Error: Message responses can be sent only once. Ignoring duplicate response "
671+ " on channel '%@ '." ,
672+ channel);
673+ }
653674 }
654675 };
655676
0 commit comments