Repository: flutter
Issue: [web]: Running the project doesn't work when building in release mode. Works when building in profile mode and while developing in debug mode. 
Labels: c: crash,engine,platform-web,e: web_canvaskit,P2,team-web,triaged-web

I'm developing a website with Flutter web. During development, everything worked as expected. No errors on Chrome or VsCode console. However, when I build it in `release` mode, flutter starts throwing a lot of errors.

When I build it in `profile` mode or try to run in `debug` mode trough VsCode, everything works as expected. 

I thought it had something to do with the optimizations made in `release` mode, so I tried to build with different optimization levels. Running the command `flutter build web --web-renderer canvaskit --release --dart2js-optimization O0` from `O0` to `O4`.

I'm running the project in a local nginx server.

<details>
<summary>Chrome console errors images</summary>


Results when building with `O0`:
![image](https://user-images.githubusercontent.com/62857460/219031667-864fd697-4f57-465b-aaa9-522493b92909.png)

Results when building with `O2`:
![image](https://user-images.githubusercontent.com/62857460/219033849-cf07d583-9d98-43b5-91e9-bf43b2c83fef.png)

Results when building with `O3`:
![O3](https://user-images.githubusercontent.com/62857460/219035068-dd50f513-417e-48f6-9256-c2b101ac79ba.png)


Results when building with `O4`:
![O4](https://user-images.githubusercontent.com/62857460/219035084-9c71c924-6923-426f-9fc4-3ad860799dfa.png)
![O4 2](https://user-images.githubusercontent.com/62857460/219035113-0d63eac9-fb88-4e1a-ae74-111f36b5c5f8.png)
</details>

Everything works as expected when building with `O1`.

Log Files: https://gist.github.com/yasukawa426/2d91ffd334f8cb377ba624ddf4dbef66]

Project code and when the errors happens in `Code Sample` section below.

Obs: I tried to run the project in multiple machines, as well as deployed in GCP with the same problem.
## Steps to Reproduce

1. Execute `flutter build web --release`
2. Run the built project

**Expected results:** <!-- what did you want to see? -->
Everything works as expected.
**Actual results:** <!-- what did you see? -->
New errors being thrown on the console. Errors that don't happen when running in `profile` or `debug` mode.
<details>
<summary>Code sample</summary>

<!--
      Please create a minimal reproducible sample that shows the problem
      and attach it below between the lines with the backticks.

      To create it you can use `flutter create bug` command and update the `main.dart` file.

      Alternatively, you can use https://dartpad.dev/
      which is capable of creating and running small Flutter apps.

      Without this we will unlikely be able to progress on the issue, and because of that
      we regretfully will have to close it.
-->

In my main.dart, I only initialize Firebase and FlutterI18n.
```dart
 WidgetsFlutterBinding.ensureInitialized();

  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );

  await FirebaseMessaging.instance.requestPermission(
    alert: true,
    announcement: true,
    badge: true,
    carPlay: false,
    criticalAlert: true,
    sound: true,
    provisional: false,
  );

  //Crashlytics não é suportado na web.
  //Checa se ta rodando na web. Caso não, ativa o crashlytics.
  if (!kIsWeb) {
    await FirebaseCrashlytics.instance.setCrashlyticsCollectionEnabled(true);
    // Pass all uncaught errors from the framework to Crashlytics.
    FlutterError.onError = FirebaseCrashlytics.instance.recordFlutterFatalError;
  }

  await FirebaseMessaging.instance.getInitialMessage();

  late final FlutterI18nDelegate flutterI18nDelegate;
  if (!kIsWeb) {
    flutterI18nDelegate = FlutterI18nDelegate(
      translationLoader: FileTranslationLoader(
        useCountryCode: true,
        fallbackFile: 'en_US',
        basePath: 'assets/i18n',
      ),
    );
  } else {
    flutterI18nDelegate = FlutterI18nDelegate(
      translationLoader: FileTranslationLoader(
        useCountryCode: true,
        fallbackFile: 'en_US',
        basePath: 'i18n',
      ),
    );
  }

  MyApp(
    key: UniqueKey(),
    flutterI18nDelegate: flutterI18nDelegate,
  ).run();
```

`MyApp` tries to authenticate the user using the [openid_client](https://pub.dev/packages/openid_client) package before running the app.
```dart
...
class MyApp extends StatelessWidget {
  final FlutterI18nDelegate flutterI18nDelegate;
  static Authenticator? authenticator;
  static FirebaseAnalytics analytics = FirebaseAnalytics.instance;
  static FirebaseAnalyticsObserver observer =
      FirebaseAnalyticsObserver(analytics: analytics);

  const MyApp({Key? key, required this.flutterI18nDelegate}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        Provider<HomeController>(
          create: (context) => HomeController(),
        ),
        Provider<UserData>(
          create: (context) => UserData(),
        ),
        Provider<StolzError>(
          create: (context) => StolzError(errorCode: 0),
        ),
        ChangeNotifierProvider<PhoneController>(
          create: (context) => PhoneController(),
        ),
        ChangeNotifierProvider<AddressController>(
          create: (context) => AddressController(),
        ),
        ChangeNotifierProvider<DeviceProvider>(
          create: (context) => DeviceProvider(),
        ),
        ChangeNotifierProvider<NotificationScreenController>(
          create: (context) => NotificationScreenController(),
        )
      ],
      child: MaterialApp(
        title: "StolzLabs",
        navigatorKey: navigatorKey,
        debugShowCheckedModeBanner: false,
        scrollBehavior: MyCustomScrollBehavior(),
        theme: StolzTheme().getTheme(),
        routes: webRoutes,
        navigatorObservers: <NavigatorObserver>[observer],
        localizationsDelegates: [
          flutterI18nDelegate,
          GlobalCupertinoLocalizations.delegate,
          GlobalMaterialLocalizations.delegate,
          GlobalWidgetsLocalizations.delegate,
        ],
        supportedLocales: const [
          Locale('pt', 'BR'),
          Locale('en', 'US'),
        ],
      ),
    );
  }

  run() async {
    if (await discover()) {
      runApp(this);
    }
  }

  ///Gera um [Authenticator] com as informações do Issuer, ClientId e Scopes, carregadas de [Network].
  ///Então, tenta ler o token do usuário para verificar se ainda está autenticado (token valido).
  ///Caso o token não estiver válido, chama [WebAuth.authenticate] para iniciar a autenticação do usuário.
  Future<bool> discover() async {
    Uri auri = Uri.parse(Network.urlBase);
    String clientId = Network.clientIDWeb;
    List<String> scopes = Network.scopes;

    var issuer = await Issuer.discover(auri);
    var client = Client(issuer, clientId);

    MyApp.authenticator ??= Authenticator(
      client,
      scopes: scopes,
    );

    TokenResponse? token = await Storage().readToken();

    if (token != null && Storage().isExpired(token.accessToken) == false) {
      Credential credential = client.createCredential(
          accessToken: token.accessToken,
          idToken: token.idToken.toCompactSerialization());
      await Storage().writeCredentials(credential);

      return true;
    }

    return await WebAuth().authenticate();
  }
}
...
```
`authenticate()` function:
```dart
...
 Future<bool> authenticate() async {
    if (MyApp.authenticator == null) {
      return false;
    }
    // get the credential
    Credential? c = await MyApp.authenticator!.credential;
    if (c == null) {
      // starts the authentication
      MyApp.authenticator!.authorize(); // this will redirect the browser
      c = await MyApp.authenticator!.credential;
      if (c == null) {
        return false;
      }
      TokenResponse token = await c.getTokenResponse();

      //Salva o token
      await Storage().setToken(token);
      return true;
    } else {
      //usuário já está autenticado.
      TokenResponse? token = await c.getTokenResponse();

      //Salva o token
      await Storage().setToken(token);

      bool isTokenExpired = Storage().isExpired(token.accessToken);

      //caso o token estiver expirado, tenta autenticar novamente.
      if (isTokenExpired) {
        MyApp.authenticator!.authorize();
        if (await MyApp.authenticator!.credential == null) {
          return false;
        }

        TokenResponse token = await c.getTokenResponse();

        await Storage().setToken(token);
        return true;
      }
      // return the user info
      return true;
    }
  }
```
And then finally, after succeding in authenticating the user, loads our home widget: 
```dart
...
class HomeInit extends StatefulWidget {
  const HomeInit({Key? key}) : super(key: key);

  @override
  State<HomeInit> createState() => _HomeInitState();
}

class _HomeInitState extends State<HomeInit> {
  ///Objeto responsável pelo carregamento da sidebar e dos itens da tela.
  final Menu _menu = Menu();

  @override
  Widget build(BuildContext context) {
    final HomeController homeController = Provider.of<HomeController>(context);
    _menu.init(context, homeController);

    return Scaffold(
      body: Row(
        children: [
          Expanded(
            child: Center(
              child: _getPage(homeController),
            ),
          ),
        ],
      ),
    );
  }

  ///Checa o index atual ([HomeController.index]) e então devolve a tela apropriada e atualiza o título da [CustomAppBar].
  Widget _getPage(HomeController homeController) {
    MenuItem? item = _menu.getMenuItem(homeController);
    return Scaffold(
      body: item!.widget,
    );
  }
}

```
`_menu` being our class responsible for loading our screens. 
And this is the first widget shown on the scaffold's body:
```dart
class _WebHomeScreenState extends State<WebHomeScreen> {
  final UserController _controller = UserController();

  Widget? f;

  @override
  Widget build(BuildContext context) {
    f ??= FutureBuilder(
        future: _controller.getMe(),
        builder: (BuildContext context, snapshot) {
          if (snapshot.hasError) {
            return UtilScreen.getProgress(context: context);
          }
          if (snapshot.hasData == false) {
            return UtilScreen.getProgress(context: context);
          }

          return _createPage(snapshot);
        });

    return f as Widget;
  }

  Widget _createPage(AsyncSnapshot snapshot) {
    User user = snapshot.data as User;
    return Center(
      child: Text(
        "${FlutterI18n.translate(context, 'label.hello')} ${user.name.first} ${user.name.last}!",
        style: Theme.of(context).textTheme.displaySmall,
      ),
    );
  }
}
```
`_controller.getMe()` loads the current logged user data from our database using a get requisition.

The errors happens after finishing the login process, when loading the home widget.
Except in `O0` which happens before the login process even start.

</details>

<details>
  <summary>Logs</summary>

<!--
      Run your application with `flutter run --verbose` and attach all the
      log output below between the lines with the backticks. If there is an
      exception, please see if the error message includes enough information
      to explain how to solve the issue. If there is a crash, please include
      the entirety of the crash log including the backtrace.
-->


<!--
     Run `flutter analyze` and attach any output of that command below.
     If there are any analysis errors, try resolving them before filing this issue.
-->

Results of `flutter analyze`

```
Analyzing stolzlabs...                                                  
No issues found! (ran in 2.4s)
```

<!-- Finally, paste the output of running `flutter doctor -v` here. -->
Results of `flutter doctor -v`. I'm using Windows 10, with pt-BR locale, as I have seen, `flutter doctor` not detecting windows version in different languages is a known bug that have already been corrected in the `master` channel.
```
[√] Flutter (Channel stable, 3.7.3, on Microsoft Windows [versÆo 10.0.19044.2486], locale pt-BR)
    • Flutter version 3.7.3 on channel stable at C:\src\flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 9944297138 (7 days ago), 2023-02-08 15:46:04 -0800
    • Engine revision 248290d6d5
    • Dart version 2.19.2
    • DevTools version 2.20.1

[X] Windows Version (Unable to confirm if installed Windows version is 10 or greater)

[√] Android toolchain - develop for Android devices (Android SDK version 33.0.0) 
    • Android SDK at C:\Users\Yasuk\AppData\Local\Android\sdk
    • Platform android-33, build-tools 33.0.0
    • Java binary at: C:\Program Files\Android\Android Studio\jre\bin\java       
    • Java version OpenJDK Runtime Environment (build 11.0.15+0-b2043.56-9505619)
    • All Android licenses accepted.

[√] Chrome - develop for the web
    • Chrome at C:\Program Files\Google\Chrome\Application\chrome.exe

[√] Android Studio (version 2022.1)
    • Android Studio at C:\Program Files\Android\Android Studio
    • 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
    • Java version OpenJDK Runtime Environment (build 11.0.15+0-b2043.56-9505619)

[√] VS Code (version 1.75.1)
    • VS Code at C:\Users\Yasuk\AppData\Local\Programs\Microsoft VS Code
    • Flutter extension version 3.58.0

[√] Connected device (2 available)
    • Chrome (web) • chrome • web-javascript • Google Chrome 110.0.5481.100
    • Edge (web)   • edge   • web-javascript • Microsoft Edge 109.0.1518.78

[√] HTTP Host Availability
    • All required HTTP hosts are available

! Doctor found issues in 1 category.
```

</details>


<!--
      Consider also attaching screenshots and/or videos to better
      illustrate the issue.

      You can upload them directly on GitHub.
      Beware that video file size is limited to 10MB.
-->