Flutter Engine
FlutterEngine Class Reference

#import <FlutterEngine.h>

Inheritance diagram for FlutterEngine:
FlutterHeadlessDartRunner

Instance Methods

(instancetype) - init
 
(instancetype) - initWithName:
 
(instancetype) - initWithName:project:
 
(instancetype) - initWithName:project:allowHeadlessExecution:
 
(BOOL) - run
 
(BOOL) - runWithEntrypoint:
 
(BOOL) - runWithEntrypoint:initialRoute:
 
(BOOL) - runWithEntrypoint:libraryURI:
 
(void) - destroyContext
 
(void) - ensureSemanticsEnabled
 
(nonnull instancetype) - initWithName:project:
 
(nonnull instancetype) - initWithName:project:allowHeadlessExecution:
 
(nonnull instancetype) - NS_UNAVAILABLE
 
(BOOL) - runWithEntrypoint:
 
(void) - shutDownEngine
 
(instancetype) - initWithScenario:withCompletion:
 
(void) - setBinaryMessenger:
 

Class Methods

(instancetype) + NS_UNAVAILABLE
 

Properties

FlutterViewControllerviewController
 
FlutterMethodChannellocalizationChannel
 
FlutterMethodChannelnavigationChannel
 
FlutterMethodChannelplatformChannel
 
FlutterMethodChanneltextInputChannel
 
FlutterBasicMessageChannellifecycleChannel
 
FlutterBasicMessageChannelsystemChannel
 
FlutterBasicMessageChannelsettingsChannel
 
FlutterBasicMessageChannelkeyEventChannel
 
NSURL * observatoryUrl
 
NSObject< FlutterBinaryMessenger > * binaryMessenger
 
NSString * isolateId
 
BOOL isGpuDisabled
 
id< FlutterBinaryMessenger > binaryMessenger
 

Detailed Description

The FlutterEngine class coordinates a single instance of execution for a FlutterDartProject. It may have zero or one FlutterViewController at a time, which can be specified via -setViewController:. FlutterViewController's initWithEngine initializer will automatically call -setViewController: for itself.

A FlutterEngine can be created independently of a FlutterViewController for headless execution. It can also persist across the lifespan of multiple FlutterViewController instances to maintain state and/or asynchronous tasks (such as downloading a large file).

A FlutterEngine can also be used to prewarm the Dart execution environment and reduce the latency of showing the Flutter screen when a FlutterViewController is created and presented. See http://flutter.dev/docs/development/add-to-app/performance for more details on loading performance.

Alternatively, you can simply create a new FlutterViewController with only a FlutterDartProject. That FlutterViewController will internally manage its own instance of a FlutterEngine, but will not guarantee survival of the engine beyond the life of the ViewController.

A newly initialized FlutterEngine will not actually run a Dart Isolate until either -runWithEntrypoint: or -runWithEntrypoint:libraryURI is invoked. One of these methods must be invoked before calling -setViewController:.

Coordinates a single instance of execution of a Flutter engine.

Definition at line 59 of file FlutterEngine.h.

Method Documentation

◆ destroyContext()

- (void) destroyContext

Destroy running context for an engine.

This method can be used to force the FlutterEngine object to release all resources. After sending this message, the object will be in an unusable state until it is deallocated. Accessing properties or sending messages to it will result in undefined behavior or runtime errors.

Definition at line 295 of file FlutterEngine.mm.

References _keyEventChannel, _lifecycleChannel, _localizationChannel, _navigationChannel, _platformChannel, _platformPlugin, _platformViewsChannel, _platformViewsController, _profiler, _profiler_metrics, _publisher, _settingsChannel, _shell, _systemChannel, _textInputChannel, _textInputPlugin, _threadHost, _viewController, flutter::Shell::Create(), fml::MessageLoop::EnsureInitializedForCurrentThread(), FML_DCHECK, FML_LOG, FlutterView::forceSoftwareRendering, fml::scoped_nsprotocol< NST >::get(), fml::MessageLoop::GetCurrent(), flutter::GetRenderingAPIForProcess(), fml::MessageLoop::GetTaskRunner(), FlutterTextInputPlugin::handleMethodCall:result:, FlutterPlatformPlugin::handleMethodCall:result:, flutter::ThreadHost::io_thread, kNumProfilerSamplesPerSec, flutter::kStartup, length, flutter::ThreadHost::profiler_thread, flutter::ThreadHost::raster_thread, flutter::ThreadHost::Reset(), fml::scoped_nsprotocol< NST >::reset(), <FlutterMessageCodec>::sharedInstance, textInputPlugin, and flutter::ThreadHost::ui_thread.

Referenced by ensureSemanticsEnabled.

295  {
296  [self resetChannels];
297  self.isolateId = nil;
298  _shell.reset();
299  _profiler.reset();
300  _threadHost.Reset();
301  _platformViewsController.reset();
302 }
std::unique_ptr< flutter::Shell > _shell
std::unique_ptr< flutter::FlutterPlatformViewsController > _platformViewsController
flutter::ThreadHost _threadHost
std::unique_ptr< flutter::SamplingProfiler > _profiler

◆ ensureSemanticsEnabled()

- (void) ensureSemanticsEnabled

Ensures that Flutter will generate a semantics tree.

This is enabled by default if certain accessibility services are turned on by the user, or when using a Simulator. This method allows a user to turn semantics on when they would not ordinarily be generated and the performance overhead is not a concern, e.g. for UI testing. Note that semantics should never be programmatically turned off, as it would potentially disable accessibility services an end user has requested.

This method must only be called after launching the engine via -runWithEntrypoint: or -runWithEntryPoint:libraryURI.

Although this method returns synchronously, it does not guarantee that a semantics tree is actually available when the method returns. It synchronously ensures that the next frame the Flutter framework creates will have a semantics tree.

You can subscribe to semantics updates via NSNotificationCenter by adding an observer for the name FlutterSemanticsUpdateNotification. The object parameter will be the FlutterViewController associated with the semantics update. This will asynchronously fire after a semantics tree has actually built (which may be some time after the frame has been rendered).

Definition at line 241 of file FlutterEngine.mm.

References _allowHeadlessExecution, _viewController, destroyContext, FML_DCHECK, lifecycleChannel, FlutterBasicMessageChannel::sendMessage:, flutter::PlatformViewIOS::SetOwnerViewController(), and viewController.

241  {
242  self.iosPlatformView->SetSemanticsEnabled(true);
243 }

◆ init()

- (instancetype) init

Default initializer for a FlutterEngine.

Threads created by this FlutterEngine will appear as "FlutterEngine #" in Instruments. The prefix can be customized using initWithName.

The engine will execute the project located in the bundle with the identifier "io.flutter.flutter.app" (the default for Flutter projects).

A newly initialized engine will not run until either -runWithEntrypoint: or -runWithEntrypoint:libraryURI: is called.

FlutterEngine created with this method will have allowHeadlessExecution set to YES. This means that the engine will continue to run regardless of whether a FlutterViewController is attached to it or not, until -destroyContext: is called or the process finishes.

Reimplemented in FlutterHeadlessDartRunner.

Definition at line 90 of file FlutterEngine.mm.

References initWithName:project:allowHeadlessExecution:.

90  {
91  return [self initWithName:@"FlutterEngine" project:nil allowHeadlessExecution:YES];
92 }

◆ initWithName:()

- (instancetype) initWithName: (NSString*)  labelPrefix

Initialize this FlutterEngine.

The engine will execute the project located in the bundle with the identifier "io.flutter.flutter.app" (the default for Flutter projects).

A newly initialized engine will not run until either -runWithEntrypoint: or -runWithEntrypoint:libraryURI: is called.

FlutterEngine created with this method will have allowHeadlessExecution set to YES. This means that the engine will continue to run regardless of whether a FlutterViewController is attached to it or not, until -destroyContext: is called or the process finishes.

Parameters
labelPrefixThe label prefix used to identify threads for this instance. Should be unique across FlutterEngine instances, and is used in instrumentation to label the threads used by this FlutterEngine.

Definition at line 94 of file FlutterEngine.mm.

References _allowHeadlessExecution, _binaryMessenger, _connections, _labelPrefix, _platformViewsController, _shell, _weakFactory, flutter::EnableTracingIfNecessary(), FML_DCHECK, initWithName:project:allowHeadlessExecution:, and FlutterBinaryMessengerRelay::parent.

94  :(NSString*)labelPrefix {
95  return [self initWithName:labelPrefix project:nil allowHeadlessExecution:YES];
96 }

◆ initWithName:project:() [1/2]

- (nonnull instancetype) initWithName: (nonnull NSString *)  labelPrefix
project: (nullable FlutterDartProject *)  project 

Initializes an engine with the given viewController.

Parameters
labelPrefixCurrently unused; in the future, may be used for labelling threads as with the iOS FlutterEngine.
projectThe project configuration. If nil, a default FlutterDartProject will be used.

◆ initWithName:project:() [2/2]

- (instancetype) initWithName: (NSString *)  labelPrefix
project: (nullable FlutterDartProject *)  project 

Initialize this FlutterEngine with a FlutterDartProject.

If the FlutterDartProject is not specified, the FlutterEngine will attempt to locate the project in a default location (the flutter_assets folder in the iOS application bundle).

A newly initialized engine will not run the FlutterDartProject until either -runWithEntrypoint: or -runWithEntrypoint:libraryURI: is called.

FlutterEngine created with this method will have allowHeadlessExecution set to YES. This means that the engine will continue to run regardless of whether a FlutterViewController is attached to it or not, until -destroyContext: is called or the process finishes.

Parameters
labelPrefixThe label prefix used to identify threads for this instance. Should be unique across FlutterEngine instances, and is used in instrumentation to label the threads used by this FlutterEngine.
projectThe FlutterDartProject to run.

Referenced by initWithScenario:withCompletion:.

◆ initWithName:project:allowHeadlessExecution:() [1/2]

- (nonnull instancetype) initWithName: (nonnull NSString *)  labelPrefix
project: (nullable FlutterDartProject *)  project
allowHeadlessExecution: (BOOL)  NS_DESIGNATED_INITIALIZER 

Initializes an engine with the given viewController.

Parameters
labelPrefixCurrently unused; in the future, may be used for labelling threads as with the iOS FlutterEngine.
projectThe project configuration. If nil, a default FlutterDartProject will be used.

◆ initWithName:project:allowHeadlessExecution:() [2/2]

- (instancetype) initWithName: (NSString *)  labelPrefix
project: (nullable FlutterDartProject *)  project
allowHeadlessExecution: (BOOL)  NS_DESIGNATED_INITIALIZER 

Initialize this FlutterEngine with a FlutterDartProject.

If the FlutterDartProject is not specified, the FlutterEngine will attempt to locate the project in a default location (the flutter_assets folder in the iOS application bundle).

A newly initialized engine will not run the FlutterDartProject until either -runWithEntrypoint: or -runWithEntrypoint:libraryURI: is called.

Parameters
labelPrefixThe label prefix used to identify threads for this instance. Should be unique across FlutterEngine instances, and is used in instrumentation to label the threads used by this FlutterEngine.
projectThe FlutterDartProject to run.
allowHeadlessExecutionWhether or not to allow this instance to continue running after passing a nil FlutterViewController to -setViewController:.

Referenced by init, and initWithName:.

◆ initWithScenario:withCompletion:()

- (instancetype) initWithScenario: (NSString*)  scenario
withCompletion: (nullable void(^)(void))  engineRunCompletion 

Provided by category FlutterEngine(ScenariosTest).

Definition at line 9 of file FlutterEngine+ScenariosTest.m.

References initWithName:project:, length, FlutterMethodChannel::methodChannelWithName:binaryMessenger:codec:, and run.

9  :(NSString*)scenario
10  withCompletion:(nullable void (^)(void))engineRunCompletion {
11  NSAssert([scenario length] != 0, @"You need to provide a scenario");
12  self = [self initWithName:[NSString stringWithFormat:@"Test engine for %@", scenario]
13  project:nil];
14  [self run];
15 
16  [self.binaryMessenger setMessageHandlerOnChannel:@"waiting_for_status"
17  binaryMessageHandler:^(NSData* message, FlutterBinaryReply reply) {
19  methodChannelWithName:@"driver"
20  binaryMessenger:self.binaryMessenger
21  codec:[FlutterJSONMethodCodec sharedInstance]];
22  [channel invokeMethod:@"set_scenario"
23  arguments:@{@"name" : scenario}];
24 
25  if (engineRunCompletion != nil) {
26  engineRunCompletion();
27  }
28  }];
29  return self;
30 }
instancetype methodChannelWithName:binaryMessenger:codec:(NSString *name, [binaryMessenger] NSObject< FlutterBinaryMessenger > *messenger, [codec] NSObject< FlutterMethodCodec > *codec)
size_t length

◆ NS_UNAVAILABLE() [1/2]

- (nonnull instancetype) NS_UNAVAILABLE

◆ NS_UNAVAILABLE() [2/2]

+ (instancetype) NS_UNAVAILABLE

◆ run()

- (BOOL) run

Runs a Dart program on an Isolate from the main Dart library (i.e. the library that contains main()), using main() as the entrypoint (the default for Flutter projects), and using "/" (the default route) as the initial route.

The first call to this method will create a new Isolate. Subsequent calls will return immediately and have no effect.

Returns
YES if the call succeeds in creating and running a Flutter Engine instance; NO otherwise.

Definition at line 578 of file FlutterEngine.mm.

References _binaryMessenger, _connections, _nextTextureId, _shell, action, binaryMessenger, FlutterBinaryReply, FML_DCHECK, flutter::GetVectorFromNSData(), FlutterDartProject::lookupKeyForAsset:, FlutterDartProject::lookupKeyForAsset:fromPackage:, flutter::ConnectionCollection::MakeErrorConnection(), FlutterBinaryMessengerRelay::parent, and value.

Referenced by initWithScenario:withCompletion:.

578  {
579  return [self runWithEntrypoint:FlutterDefaultDartEntrypoint
580  libraryURI:nil
581  initialRoute:FlutterDefaultInitialRoute];
582 }

◆ runWithEntrypoint:() [1/2]

- (BOOL) runWithEntrypoint: (nullable NSString *)  entrypoint

Runs a Dart program on an Isolate from the main Dart library (i.e. the library that contains main()).

The first call to this method will create a new Isolate. Subsequent calls will return immediately.

Parameters
entrypointThe name of a top-level function from the same Dart library that contains the app's main() function. If this is nil, it will default to main(). If it is not the app's main() function, that function must be decorated with @pragma(vm:entry-point) to ensure the method is not tree-shaken by the Dart compiler.
Returns
YES if the call succeeds in creating and running a Flutter Engine instance; NO otherwise.

◆ runWithEntrypoint:() [2/2]

- (BOOL) runWithEntrypoint: (nullable NSString *)  entrypoint

Runs a Dart program on an Isolate from the main Dart library (i.e. the library that contains main()), using "/" (the default route) as the initial route.

The first call to this method will create a new Isolate. Subsequent calls will return immediately and have no effect.

Parameters
entrypointThe name of a top-level function from the same Dart library that contains the app's main() function. If this is FlutterDefaultDartEntrypoint (or nil) it will default to main(). If it is not the app's main() function, that function must be decorated with @pragma(vm:entry-point) to ensure the method is not tree-shaken by the Dart compiler.
Returns
YES if the call succeeds in creating and running a Flutter Engine instance; NO otherwise.

◆ runWithEntrypoint:initialRoute:()

- (BOOL) runWithEntrypoint: (nullable NSString *)  entrypoint
initialRoute: (nullable NSString *)  initialRoute 

Runs a Dart program on an Isolate from the main Dart library (i.e. the library that contains main()).

The first call to this method will create a new Isolate. Subsequent calls will return immediately and have no effect.

Parameters
entrypointThe name of a top-level function from the same Dart library that contains the app's main() function. If this is FlutterDefaultDartEntrypoint (or nil), it will default to main(). If it is not the app's main() function, that function must be decorated with @pragma(vm:entry-point) to ensure the method is not tree-shaken by the Dart compiler.
initialRouteThe name of the initial Flutter Navigator Route to load. If this is FlutterDefaultInitialRoute (or nil), it will default to the "/" route.
Returns
YES if the call succeeds in creating and running a Flutter Engine instance; NO otherwise.

◆ runWithEntrypoint:libraryURI:()

- (BOOL) runWithEntrypoint: (nullable NSString *)  entrypoint
libraryURI: (nullable NSString *)  uri 

Runs a Dart program on an Isolate using the specified entrypoint and Dart library, which may not be the same as the library containing the Dart program's main() function.

The first call to this method will create a new Isolate. Subsequent calls will return immediately and have no effect.

Parameters
entrypointThe name of a top-level function from a Dart library. If this is FlutterDefaultDartEntrypoint (or nil); this will default to main(). If it is not the app's main() function, that function must be decorated with @pragma(vm:entry-point) to ensure the method is not tree-shaken by the Dart compiler.
uriThe URI of the Dart library which contains the entrypoint method. IF nil, this will default to the same library as the main() function in the Dart program.
Returns
YES if the call succeeds in creating and running a Flutter Engine instance; NO otherwise.

◆ setBinaryMessenger:()

- (void) setBinaryMessenger: (FlutterBinaryMessengerRelay *)  binaryMessenger

Provided by category FlutterEngine(Test).

◆ shutDownEngine()

- (void) shutDownEngine

Shuts the Flutter engine if it is running. The FlutterEngine instance must always be shutdown before it may be collected. Not shutting down the FlutterEngine instance before releasing it will result in the leak of that engine instance.

Note: Called from dealloc. Should not use accessors or other methods.

Definition at line 522 of file FlutterEngine.mm.

References _engine, _messageHandlers, _textures, FlutterBinaryReply, FlutterEngineDeinitialize(), FlutterEngineGetCurrentTime(), FlutterEngineMarkExternalTextureFrameAvailable(), FlutterEngineRegisterExternalTexture(), FlutterEngineRunTask(), FlutterEngineSendPlatformMessage(), FlutterEngineShutdown(), FlutterEngineUnregisterExternalTexture(), FlutterPlatformMessageCreateResponseHandle(), FlutterPlatformMessageReleaseResponseHandle(), kSuccess, FlutterPlatformMessage::struct_size, FlutterExternalTextureGL::textureID, and user_data.

522  {
523  if (_engine == nullptr) {
524  return;
525  }
526 
528  if (result != kSuccess) {
529  NSLog(@"Could not de-initialize the Flutter engine: error %d", result);
530  }
531 
532  // Balancing release for the retain in the task runner dispatch table.
533  CFRelease((CFTypeRef)self);
534 
535  result = FlutterEngineShutdown(_engine);
536  if (result != kSuccess) {
537  NSLog(@"Failed to shut down Flutter engine: error %d", result);
538  }
539  _engine = nullptr;
540 }
FLUTTER_EXPORT FlutterEngineResult FlutterEngineDeinitialize(FLUTTER_API_SYMBOL(FlutterEngine) engine)
Stops running the Flutter engine instance. After this call, the embedder is also guaranteed that no m...
Definition: embedder.cc:1206
FlutterEngineResult FlutterEngineShutdown(FLUTTER_API_SYMBOL(FlutterEngine) engine)
Shuts down a Flutter engine instance. The engine handle is no longer valid for any calls in the embed...
Definition: embedder.cc:1218
fml::scoped_nsobject< FlutterEngine > _engine
FlutterEngineResult
Definition: embedder.h:65

Property Documentation

◆ binaryMessenger [1/2]

- (id<FlutterBinaryMessenger>) binaryMessenger
readnonatomicassign

The FlutterBinaryMessenger for communicating with this engine.

Definition at line 73 of file FlutterEngine.h.

◆ binaryMessenger [2/2]

- (id< FlutterBinaryMessenger >) binaryMessenger
readnonatomicassign

The FlutterBinaryMessenger associated with this FlutterEngine (used for communicating with channels).

Definition at line 346 of file FlutterEngine.h.

Referenced by FlutterEngineRegistrar::initWithPlugin:flutterEngine:, and run.

◆ isGpuDisabled

- (BOOL) isGpuDisabled
readwritenonatomicassign

Whether or not GPU calls are allowed.

Typically this is set when the app is backgrounded and foregrounded.

Definition at line 360 of file FlutterEngine.h.

◆ isolateId

- (NSString*) isolateId
readnonatomiccopy

The UI Isolate ID of the engine.

This property will be nil if the engine is not running.

Definition at line 353 of file FlutterEngine.h.

◆ keyEventChannel

- (FlutterBasicMessageChannel *) keyEventChannel
readnonatomicassign

The FlutterBasicMessageChannel used for communicating key events from physical keyboards

Can be nil after destroyContext is called.

Definition at line 331 of file FlutterEngine.h.

◆ lifecycleChannel

- (FlutterBasicMessageChannel *) lifecycleChannel
readnonatomicassign

The FlutterBasicMessageChannel used to communicate app lifecycle events to the Dart Isolate.

Can be nil after destroyContext is called.

See also
Lifecycle Channel

Definition at line 304 of file FlutterEngine.h.

Referenced by ensureSemanticsEnabled.

◆ localizationChannel

- (FlutterMethodChannel *) localizationChannel
readnonatomicassign

The FlutterMethodChannel used for localization related platform messages, such as setting the locale.

Can be nil after destroyContext is called.

Definition at line 264 of file FlutterEngine.h.

◆ navigationChannel

- (FlutterMethodChannel *) navigationChannel
readnonatomicassign

The FlutterMethodChannel used for navigation related platform messages.

Can be nil after destroyContext is called.

See also
Navigation Channel
Navigator Widget

Definition at line 274 of file FlutterEngine.h.

◆ observatoryUrl

- (NSURL *) observatoryUrl
readnonatomicassign

The NSURL of the observatory for the service isolate.

This is only set in debug and profile runtime modes, and only after the observatory service is ready. In release mode or before the observatory has started, it returns nil.

Definition at line 340 of file FlutterEngine.h.

◆ platformChannel

- (FlutterMethodChannel *) platformChannel
readnonatomicassign

The FlutterMethodChannel used for core platform messages, such as information about the screen orientation.

Can be nil after destroyContext is called.

Definition at line 282 of file FlutterEngine.h.

◆ settingsChannel

- (FlutterBasicMessageChannel *) settingsChannel
readnonatomicassign

The FlutterBasicMessageChannel used for communicating user settings such as clock format and text scale.

Can be nil after destroyContext is called.

Definition at line 323 of file FlutterEngine.h.

◆ systemChannel

- (FlutterBasicMessageChannel *) systemChannel
readnonatomicassign

The FlutterBasicMessageChannel used for communicating system events, such as memory pressure events.

Can be nil after destroyContext is called.

See also
System Channel

Definition at line 315 of file FlutterEngine.h.

◆ textInputChannel

- (FlutterMethodChannel *) textInputChannel
readnonatomicassign

The FlutterMethodChannel used to communicate text input events to the Dart Isolate.

Can be nil after destroyContext is called.

See also
Text Input Channel

Definition at line 293 of file FlutterEngine.h.

◆ viewController

- (FlutterViewController *) viewController
readwritenonatomicweak

Sets the FlutterViewController for this instance. The FlutterEngine must be running (e.g. a successful call to -runWithEntrypoint: or -runWithEntrypoint:libraryURI) before calling this method. Callers may pass nil to remove the viewController and have the engine run headless in the current process.

A FlutterEngine can only have one FlutterViewController at a time. If there is already a FlutterViewController associated with this instance, this method will replace the engine's current viewController with the newly specified one.

Setting the viewController will signal the engine to start animations and drawing, and unsetting it will signal the engine to stop animations and drawing. However, neither will impact the state of the Dart program's execution.

The FlutterViewController associated with this engine, if any.

Definition at line 256 of file FlutterEngine.h.

Referenced by ensureSemanticsEnabled, and FlutterViewController::initWithEngine:nibName:bundle:.


The documentation for this class was generated from the following files: