Repository: flutter
Issue: [add-to-app] SystemChrome.setPreferredOrientations + use of cached flutter engine shows black screen when starting Flutter activity
Labels: platform-android,engine,a: existing-apps,a: layout,has reproducible steps,P2,team-android,triaged-android,found in release: 3.16,found in release: 3.19

### Steps to reproduce

1. Create an Android app
2. Integrate a Flutter module (https://docs.flutter.dev/add-to-app/android/project-setup?tab=without-android-studio)
3. Add a button to open a Flutter screen (https://docs.flutter.dev/add-to-app/android/add-flutter-screen?tab=prewarm-engine-kotlin-tab)
4. Follow step 3 to use a cached FlutterEngine (https://docs.flutter.dev/add-to-app/android/add-flutter-screen?tab=prewarm-engine-kotlin-tab#step-3-optional-use-a-cached-flutterengine)
5. On the Flutter module side, open the `lib/main.dart` file and try to set device orientation with `SystemChrome` API before `runApp()`
```dart
Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
  runApp(const MyApp());
}
```

### Expected results

Flutter activity opens without issue

### Actual results

Black screen, the future returned from `setDeviceOrientations` seems to never complete

Either remove the call to `setDeviceOrientations` or do not use the cached FlutterEngine remove the issue

### Code sample

I have an entire repository example here : https://github.com/woprandi/MyApplication

<details open><summary>Code sample (Flutter module main.dart)</summary>

```dart
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or press Run > Flutter Hot Reload in a Flutter IDE). Notice that the
        // counter didn't reset back to zero; the application is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      // This call to setState tells the Flutter framework that something has
      // changed in this State, which causes it to rerun the build method below
      // so that the display can reflect the updated values. If we changed
      // _counter without calling setState(), then the build method would not be
      // called again, and so nothing would appear to happen.
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: Center(
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: Column(
          // Column is also a layout widget. It takes a list of children and
          // arranges them vertically. By default, it sizes itself to fit its
          // children horizontally, and tries to be as tall as its parent.
          //
          // Invoke "debug painting" (press "p" in the console, choose the
          // "Toggle Debug Paint" action from the Flutter Inspector in Android
          // Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
          // to see the wireframe for each widget.
          //
          // Column has various properties to control how it sizes itself and
          // how it positions its children. Here we use mainAxisAlignment to
          // center the children vertically; the main axis here is the vertical
          // axis because Columns are vertical (the cross axis would be
          // horizontal).
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headlineMedium,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

```

</details>


<details open><summary>Code sample (MainActivity.kt)</summary>

```kotlin
package com.example.myapplication

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.example.myapplication.ui.theme.MyApplicationTheme
import io.flutter.embedding.android.FlutterActivity

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MyApplicationTheme {
                // A surface container using the 'background' color from the theme
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colorScheme.background
                ) {
                    Button(onClick = {
                        //startActivity(FlutterActivity.createDefaultIntent(this))
                        startActivity(
                            FlutterActivity
                                .withCachedEngine("my_engine_id")
                                .build(this)
                        )
                    }) {
                      Text("Open Flutter module")
                    }
                }
            }
        }
    }
}
```

```kotlin
package com.example.myapplication

import android.app.Application
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.embedding.engine.FlutterEngineCache
import io.flutter.embedding.engine.dart.DartExecutor

class App : Application() {
    lateinit var flutterEngine : FlutterEngine

    override fun onCreate() {
        super.onCreate()

        // Instantiate a FlutterEngine.
        flutterEngine = FlutterEngine(this)

        // Start executing Dart code to pre-warm the FlutterEngine.
        flutterEngine.dartExecutor.executeDartEntrypoint(
            DartExecutor.DartEntrypoint.createDefault()
        )

        // Cache the FlutterEngine to be used by FlutterActivity.
        FlutterEngineCache
            .getInstance()
            .put("my_engine_id", flutterEngine)
    }
}
```
</details>

### Screenshots or Video

<details open>
<summary>Screenshots / Video demonstration</summary>

[untitled.webm](https://github.com/flutter/flutter/assets/1449422/fc5aa1ae-99f3-4d00-8d73-d67ad1727593)

</details>


### Logs

<details open><summary>Logs</summary>

```console
2024-01-25 16:26:49.754 16767-16767 nativeloader            com.example.myapplication            D  Configuring clns-6 for other apk /data/app/~~H7Feiqs7V1W4pLThKFI-YQ==/com.example.myapplication-XcJLIQOcl4SmDgR8THMtUA==/base.apk. target_sdk_version=34, uses_libraries=, library_path=/data/app/~~H7Feiqs7V1W4pLThKFI-YQ==/com.example.myapplication-XcJLIQOcl4SmDgR8THMtUA==/lib/x86_64:/data/app/~~H7Feiqs7V1W4pLThKFI-YQ==/com.example.myapplication-XcJLIQOcl4SmDgR8THMtUA==/base.apk!/lib/x86_64, permitted_path=/data:/mnt/expand:/data/user/0/com.example.myapplication
2024-01-25 16:26:49.770 16767-16767 GraphicsEnvironment     com.example.myapplication            V  Currently set values for:
2024-01-25 16:26:49.770 16767-16767 GraphicsEnvironment     com.example.myapplication            V    angle_gl_driver_selection_pkgs=[]
2024-01-25 16:26:49.770 16767-16767 GraphicsEnvironment     com.example.myapplication            V    angle_gl_driver_selection_values=[]
2024-01-25 16:26:49.772 16767-16767 GraphicsEnvironment     com.example.myapplication            V  ANGLE GameManagerService for com.example.myapplication: false
2024-01-25 16:26:49.772 16767-16767 GraphicsEnvironment     com.example.myapplication            V  com.example.myapplication is not listed in per-application setting
2024-01-25 16:26:49.772 16767-16767 GraphicsEnvironment     com.example.myapplication            V  Neither updatable production driver nor prerelease driver is supported.
2024-01-25 16:26:49.923 16767-16825 ResourceExtractor       com.example.myapplication            I  Found extracted resources res_timestamp-1-1706196335560
2024-01-25 16:26:49.923 16767-16825 ResourceExtractor       com.example.myapplication            I  Resource version mismatch res_timestamp-1-1706196408109
2024-01-25 16:26:50.580 16767-16825 ResourceExtractor       com.example.myapplication            I  Extracted baseline resource assets/flutter_assets/kernel_blob.bin
2024-01-25 16:26:50.582 16767-16825 ResourceExtractor       com.example.myapplication            I  Extracted baseline resource assets/flutter_assets/vm_snapshot_data
2024-01-25 16:26:50.725 16767-16825 ResourceExtractor       com.example.myapplication            I  Extracted baseline resource assets/flutter_assets/isolate_snapshot_data
2024-01-25 16:26:50.734 16767-16767 e.myapplication         com.example.myapplication            W  type=1400 audit(0.0:1928): avc:  denied  { read } for  name="max_map_count" dev="proc" ino=126972 scontext=u:r:untrusted_app:s0:c193,c256,c512,c768 tcontext=u:object_r:proc_max_map_count:s0 tclass=file permissive=0 app=com.example.myapplication
2024-01-25 16:26:50.753 16767-16767 libEGL                  com.example.myapplication            D  loaded /vendor/lib64/egl/libEGL_emulation.so
2024-01-25 16:26:50.758 16767-16767 libEGL                  com.example.myapplication            D  loaded /vendor/lib64/egl/libGLESv1_CM_emulation.so
2024-01-25 16:26:50.765 16767-16767 libEGL                  com.example.myapplication            D  loaded /vendor/lib64/egl/libGLESv2_emulation.so
2024-01-25 16:26:51.057 16767-16837 flutter                 com.example.myapplication            I  The Dart VM service is listening on http://127.0.0.1:39909/gL_eo2m52IU=/
2024-01-25 16:26:51.147 16767-16767 Compatibil...geReporter com.example.myapplication            D  Compat change id reported: 237531167; UID 10193; state: DISABLED
2024-01-25 16:26:51.150 16767-16767 OpenGLRenderer          com.example.myapplication            W  Unknown dataspace 0
2024-01-25 16:26:51.165 16767-16767 Choreographer           com.example.myapplication            I  Skipped 82 frames!  The application may be doing too much work on its main thread.
2024-01-25 16:26:51.386 16767-16767 e.myapplication         com.example.myapplication            W  Method java.lang.Object androidx.compose.runtime.snapshots.SnapshotStateMap.mutate(kotlin.jvm.functions.Function1) failed lock verification and will run slower.
                                                                                                    Common causes for lock verification issues are non-optimized dex code
                                                                                                    and incorrect proguard optimizations.
2024-01-25 16:26:51.387 16767-16767 e.myapplication         com.example.myapplication            W  Method void androidx.compose.runtime.snapshots.SnapshotStateMap.update(kotlin.jvm.functions.Function1) failed lock verification and will run slower.
2024-01-25 16:26:51.388 16767-16767 e.myapplication         com.example.myapplication            W  Method boolean androidx.compose.runtime.snapshots.SnapshotStateMap.removeIf$runtime_release(kotlin.jvm.functions.Function1) failed lock verification and will run slower.
2024-01-25 16:26:51.521 16767-16767 e.myapplication         com.example.myapplication            W  Method boolean androidx.compose.runtime.snapshots.SnapshotStateList.conditionalUpdate(kotlin.jvm.functions.Function1) failed lock verification and will run slower.
2024-01-25 16:26:51.522 16767-16767 e.myapplication         com.example.myapplication            W  Method java.lang.Object androidx.compose.runtime.snapshots.SnapshotStateList.mutate(kotlin.jvm.functions.Function1) failed lock verification and will run slower.
2024-01-25 16:26:51.523 16767-16767 e.myapplication         com.example.myapplication            W  Method void androidx.compose.runtime.snapshots.SnapshotStateList.update(kotlin.jvm.functions.Function1) failed lock verification and will run slower.
2024-01-25 16:26:51.637 16767-16838 OpenGLRenderer          com.example.myapplication            W  Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
2024-01-25 16:26:51.638 16767-16838 OpenGLRenderer          com.example.myapplication            W  Failed to initialize 101010-2 format, error = EGL_SUCCESS
2024-01-25 16:26:51.654 16767-16838 Gralloc4                com.example.myapplication            I  mapper 4.x is not supported
2024-01-25 16:26:51.815 16767-16838 OpenGLRenderer          com.example.myapplication            E  Unable to match the desired swap behavior.
2024-01-25 16:26:51.882 16767-16780 OpenGLRenderer          com.example.myapplication            I  Davey! duration=2078ms; Flags=1, FrameTimelineVsyncId=972730, IntendedVsync=47232369184667, Vsync=47233735851279, InputEventId=0, HandleInputStart=47233742473526, AnimationStart=47233742480381, PerformTraversalsStart=47233742674979, DrawStart=47234394056571, FrameDeadline=47232385851333, FrameInterval=47233741309039, FrameStartTime=16666666, SyncQueued=47234406392966, SyncStart=47234411526866, IssueDrawCommandsStart=47234414025803, SwapBuffers=47234442699573, FrameCompleted=47234452702949, DequeueBufferDuration=8836, QueueBufferDuration=573432, GpuCompleted=47234452702949, SwapBuffersCompleted=47234450214045, DisplayPresentTime=0, CommandSubmissionCompleted=47234442699573, 
2024-01-25 16:26:52.008 16767-16767 Choreographer           com.example.myapplication            I  Skipped 44 frames!  The application may be doing too much work on its main thread.
2024-01-25 16:26:56.416 16767-16848 ProfileInstaller        com.example.myapplication            D  Installing profile for com.example.myapplication
2024-01-25 16:26:58.088 16767-16838 EGL_emulation           com.example.myapplication            D  app_time_stats: avg=2071.22ms min=31.24ms max=5185.25ms count=3
2024-01-25 16:26:58.184 16767-16767 AutofillManager         com.example.myapplication            D  Fill dialog is enabled:false, hints=[password, passwordAuto, creditCardNumber, creditCardSecurityCode, creditCardExpirationDate]
2024-01-25 16:26:58.206 16767-16767 e.myapplication         com.example.myapplication            W  Accessing hidden method Landroid/view/accessibility/AccessibilityNodeInfo;->getSourceNodeId()J (unsupported,test-api, reflection, allowed)
2024-01-25 16:26:58.206 16767-16767 e.myapplication         com.example.myapplication            W  Accessing hidden method Landroid/view/accessibility/AccessibilityRecord;->getSourceNodeId()J (unsupported, reflection, allowed)
2024-01-25 16:26:58.206 16767-16767 e.myapplication         com.example.myapplication            W  Accessing hidden field Landroid/view/accessibility/AccessibilityNodeInfo;->mChildNodeIds:Landroid/util/LongArray; (unsupported, reflection, allowed)
2024-01-25 16:26:58.207 16767-16767 e.myapplication         com.example.myapplication            W  Accessing hidden method Landroid/util/LongArray;->get(I)J (unsupported, reflection, allowed)
2024-01-25 16:26:58.369 16767-16838 OpenGLRenderer          com.example.myapplication            E  Unable to match the desired swap behavior.

```

</details>


### Flutter Doctor output

<details open><summary>Doctor output</summary>

```console
[✓] Flutter (Channel stable, 3.16.8, on Fedora Linux 39 (Workstation Edition) 6.6.12-200.fc39.x86_64, locale fr_FR.UTF-8)
    • Flutter version 3.16.8 on channel stable at /home/william/Documents/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 67457e669f (il y a 9 jours), 2024-01-16 16:22:29 -0800
    • Engine revision 6e2ea58a5c
    • Dart version 3.2.5
    • DevTools version 2.28.5

[✓] Android toolchain - develop for Android devices (Android SDK version 34.0.0)
    • Android SDK at /home/william/Android/Sdk
    • Platform android-34, build-tools 34.0.0
    • Java binary at: /home/william/.local/share/JetBrains/Toolbox/apps/android-studio/jbr/bin/java
    • Java version OpenJDK Runtime Environment (build 17.0.7+0-17.0.7b1000.6-10550314)
    • All Android licenses accepted.

[✓] Chrome - develop for the web
    • Chrome at google-chrome

[✓] Linux toolchain - develop for Linux desktop
    • clang version 17.0.6 (Fedora 17.0.6-1.fc39)
    • cmake version 3.27.7
    • ninja version 1.11.1
    • pkg-config version 1.9.5

[✓] Android Studio (version 2023.1)
    • Android Studio at /home/william/.local/share/JetBrains/Toolbox/apps/android-studio
    • Flutter plugin version 77.1.2
    • Dart plugin version 222.4582
    • Java version OpenJDK Runtime Environment (build 17.0.7+0-17.0.7b1000.6-10550314)

[✓] IntelliJ IDEA Community Edition (version 2023.3)
    • IntelliJ at /home/william/.local/share/JetBrains/Toolbox/apps/intellij-idea-community-edition
    • Flutter plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/6351-dart

[✓] VS Code (version 1.85.2)
    • VS Code at /usr/share/code
    • Flutter extension version 3.80.0

[✓] Connected device (3 available)
    • sdk gphone64 x86 64 (mobile) • emulator-5554 • android-x64    • Android 14 (API 34) (emulator)
    • Linux (desktop)              • linux         • linux-x64      • Fedora Linux 39 (Workstation Edition) 6.6.12-200.fc39.x86_64
    • Chrome (web)                 • chrome        • web-javascript • Google Chrome 120.0.6099.224

[✓] Network resources
    • All expected network resources are available.

• No issues found!
```

</details>