Nitant Sood
Nitant Sood

Reputation: 93

Reset FlutterFragment content using Flutter Engine while using FlutterFragment

I am using a Flutter module inside my Android Application. I have defined a global Flutter Engine in a pre heated state in my Activity and is attaching it to a FlutterFragment as and when required in a particular Scenario. Below is pre heated engine called once the onCreate()on Activity is triggered.

void setupFlutterEngine(){
        FlutterEngine flutterEngine=new FlutterEngine(getApplicationContext());

//        Start executing Dart code in the FlutterEngine.
        flutterEngine.getDartExecutor().executeDartEntrypoint(
                DartExecutor.DartEntrypoint.createDefault()
        );

//      Cache the pre-warmed FlutterEngine to be used later by FlutterFragment.
        FlutterEngineCache
                .getInstance()
                .put(FLUTTER_ENGINE_CACHE_TAG, flutterEngine);

    }

Everything is working fine, I am instantiating and adding the cached engine to my FlutterFragment as below :

FlutterEngine flutterEngine=FlutterEngineCache.getInstance().get(FLUTTER_ENGINE_CACHE_TAG);

flutterMethodChannel = new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), methodChannelTag);

flutterMethodChannel.setMethodCallHandler(new MethodChannel.MethodCallHandler() {
            @Override
            public void onMethodCall(@NonNull MethodCall call, @NonNull MethodChannel.Result result) {
                
            }
        });

        GeneratedPluginRegistrant.registerWith(flutterEngine); 

flutterFragment = FlutterFragment
                .withCachedEngine(FLUTTER_ENGINE_CACHE_TAG)
                .renderMode(RenderMode.surface)
                .transparencyMode(TransparencyMode.opaque)
                .shouldAttachEngineToActivity(true)
                .build();

I want to finish the current view of flutter module when the fragment is destroyed but do not want to destroy the engine, I would like to reuse the FlutterEngine and want to re-start from the very first screen under main() method in Flutter module when the fragment is again added.

Upvotes: 9

Views: 1113

Answers (1)

Mohmmaed-Amleh
Mohmmaed-Amleh

Reputation: 438

if your issue like this one https://github.com/flutter/flutter/issues/65829

i find a solution for this problem, just override this method on FlutterActivity:

    @Override
    public void onFlutterUiNoLongerDisplayed() {
    super.onFlutterUiNoLongerDisplayed();
    if(isFinishing()){
        MethodChannel channel = new MethodChannel(cachedEngine.getDartExecutor().getBinaryMessenger(), "your_plugin");
        channel.invokeMethod("pop", null);
    }
}

and from your flutter module pop the route .

Upvotes: 0

Related Questions