@@ -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 */
@@ -243,6 +250,8 @@ - (instancetype)initWithName:(NSString*)labelPrefix
243250 _allowHeadlessExecution = allowHeadlessExecution;
244251 _semanticsEnabled = NO ;
245252 _viewProvider = [[FlutterViewEngineProvider alloc ] initWithEngine: self ];
253+ _isResponseValid = [[NSMutableArray alloc ] initWithCapacity: 1 ];
254+ [_isResponseValid addObject: @YES ];
246255
247256 _embedderAPI.struct_size = sizeof (FlutterEngineProcTable);
248257 FlutterEngineGetProcAddresses (&_embedderAPI);
@@ -263,6 +272,10 @@ - (instancetype)initWithName:(NSString*)labelPrefix
263272}
264273
265274- (void )dealloc {
275+ @synchronized (_isResponseValid) {
276+ [_isResponseValid removeAllObjects ];
277+ [_isResponseValid addObject: @NO ];
278+ }
266279 [self shutDownEngine ];
267280 if (_aotData) {
268281 _embedderAPI.CollectAOTData (_aotData);
@@ -639,17 +652,24 @@ - (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 ;
643657 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);
658+ @synchronized (isResponseValid) {
659+ if (![isResponseValid[0 ] boolValue ]) {
660+ // Ignore, engine was killed.
661+ return ;
662+ }
663+ if (responseHandle) {
664+ _embedderAPI.SendPlatformMessageResponse (weakSelf->_engine , responseHandle,
665+ static_cast <const uint8_t *>(response.bytes ),
666+ response.length );
667+ responseHandle = NULL ;
668+ } else {
669+ NSLog (@" Error: Message responses can be sent only once. Ignoring duplicate response "
670+ " on channel '%@ '." ,
671+ channel);
672+ }
653673 }
654674 };
655675
0 commit comments