Skip to content

Improve embedded FlutterFragment's back button navigation delegation #67011

@math1man

Description

@math1man

Add-to-app Flutter can be used in two ways. It can be embedded in its own dedicated activity, or it can share an activity with other native code. The former strategy works pretty well from what I've seen, however, it lacks a lot of flexibility because it means you can't really put Flutter and native UI side by side. The latter solution on the other hand has some issues. This issue involve navigation.

The FlutterFragment documents that the activity should call through to the fragment's onBackPressed() method. This has two problems:

  1. If the FlutterFragment is nested inside a stack of fragments, this call through can be pretty tedious.
  2. It's difficult for the native code to decide whether back behavior should be handled natively, or by flutter.

Both of these issues can be resolved using AndroidX's OnBackPressedCallback API. They high level summary of the API is that it allows fragments to register an OnBackPressedCallback to the fragment's activity. This instantly solves problem 1, but problem 2 requires a bit more work.

OnBackPressedCallbacks have an internal enabled state that controls whether the activity should delegate to the callback or to its own logic. (The callbacks are also associated with the fragment's lifecycle to ensure that they're automatically disabled when the fragment is detached, and there's also a complex algorithm to determine callback precedence if multiple are active simultaneously). It should be possible to add functionality to Flutter's navigation channel such that Dart code can call through to update the enabled state of the callback, resolving problem 2. There's a small chance for race conditions updating the enabled state because of the async nature of channels, but this is still a strict improvement. There are probably ways to improve the raciness too, I just haven't thought too much about them.

Metadata

Metadata

Assignees

No one assigned

    Labels

    P2Important issues not at the top of the work lista: existing-appsIntegration with existing apps via the add-to-app flowc: new featureNothing broken; request for a new capabilityc: proposalA detailed proposal for a change to Fluttercustomer: googleVarious Google teamsengineflutter/engine related. See also e: labels.f: routesNavigator, Router, and related APIs.frameworkflutter/packages/flutter repository. See also f: labels.platform-androidAndroid applications specificallyteam-androidOwned by Android platform teamtriaged-androidTriaged by Android platform team

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions