Repository: flutter
Issue: MaterialApp not building fully on Locale('ar') test
Labels: a: tests,framework,f: material design,a: internationalization,has reproducible steps,P3,team-design,triaged-design,found in release: 3.13,found in release: 3.14

### Is there an existing issue for this?

- [X] I have searched the [existing issues](https://github.com/flutter/flutter/issues)
- [X] I have read the [guide to filing a bug](https://flutter.dev/docs/resources/bug-reports)

### Steps to reproduce

Unsure if this is a bug or I have just managed to break my project.

I am building a project for internationalization to be used in other projects later on. The project is using l10n and BLoC for state management. The supported languages are 'en' (default), 'ar', 'de', 'es', etc.
The project works without any issues when run on a connected android device. However, automated tests fail with certain locales ('ar', 'be', 'fa', etc.) as the MaterialApp tree isn't building fully.
After encountering the error and being unable to solve it I, to ensure I haven't introduced errors during the design, have started again from a blank canvas only copy-pasting my code snippets, but setting up the l10n, pubspec, etc. from scratch. The error remains that non-latin scripts fail in tests.
Additionally, after unplugging the android device (after successfully running and stopping the app) any non-latin languages that have not been triggered while the phone was connected also fail to build. The app does not default to 'en', but ignores all locale changes.

I'm unsure if I am missing some initialization - WidgetsFlutterBinding.ensureInitialized(); is initialized in main() - or some boolean I need to trigger.

If this is not a bug, please close and my apologies.

### Expected results

Material App building fully (using Locale('ar') and starting HomePage. Test to be able to find the HomePage element - final context = tester.element(find.byType(HomePage)); - this works successfully on locales like 'en', 'de', 'es' ...

### Actual results

Material App stopping build halfway through (not building title, directionality, debugBanner, home etc.). Test failing as it cannot find the HomePage

### Code sample

<details><summary>Code sample</summary>

```dart
import 'package:advanced_internationalization/home/home.dart';
import 'package:advanced_internationalization/l10n/l10n.dart';
import 'package:advanced_internationalization/settings/settings.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_localized_locales/flutter_localized_locales.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:settings_repository/settings_repository.dart';

/// The top-level widget representing the entire application.
class App extends StatelessWidget {
  /// Creates an instance of the [App] widget and initializes the required
  /// BLoc providers.
  const App({
    required this.settingsRepository,
    super.key,
  });

  /// The [settingsRepository] is responsible for managing the application's
  /// settings, such as locale and theme preferences.
  final SettingsRepository settingsRepository;

  @override
  Widget build(BuildContext context) {
    return RepositoryProvider<SettingsRepository>.value(
      value: settingsRepository,
      child: BlocProvider(
        create: (context) => LocaleSettingsBloc(
          settingsRepository: context.read<SettingsRepository>(),
        )..add(const GetLocaleSettings()),
        child: const AppView(),
      ),
    );
  }
}

/// The root for the [MaterialApp].
class AppView extends StatefulWidget {
  /// Creates an instance of the [AppView] widget.
  ///
  /// This widget acts as the root for the material application and listens to
  /// device locale changes.
  const AppView({super.key});

  @override
  State<AppView> createState() => _AppViewState();
}

class _AppViewState extends State<AppView> with WidgetsBindingObserver {
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void didChangeLocales(List<Locale>? locales) {
    context.read<LocaleSettingsBloc>().add(ChangeDeviceLocale(locales!.first));
    super.didChangeLocales(locales);
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<LocaleSettingsBloc, LocaleSettingsState>(
      builder: (context, state) {
        return MaterialApp(
          title: 'Flutter Localizations',
          theme: ThemeData(primarySwatch: Colors.blue),
          supportedLocales: AppLocalizations.supportedLocales,
          locale: state.selectedLocale,
          localeListResolutionCallback: (locales, supportedLocales) {
            if (state.deviceLocale == null) {
              // Setting initial device locale
              context
                  .read<LocaleSettingsBloc>()
                  .add(ChangeDeviceLocale(locales!.first));
            }
            return basicLocaleListResolution(locales, supportedLocales);
          },
          localizationsDelegates: const [
            ...AppLocalizations.localizationsDelegates,
            LocaleNamesLocalizationsDelegate(),
          ],
          home: const HomePage(),
        );
      },
    );
  }
}


/// Testing file
class MockSettingsRepository extends Mock implements SettingsRepository {}

void main() {
  group('Locale Integration Tests', () {
    late MockSettingsRepository mockSettingsRepository;

    final supportedLocale = AppLocalizations.supportedLocales[1];
    final supportedLocaleAlternative = AppLocalizations.supportedLocales[2];
    final supportedLocalesList = [supportedLocale, supportedLocaleAlternative];

    setUp(() {
      mockSettingsRepository = MockSettingsRepository();
    });

    testWidgets('Start in first device locale (supported)',
        (WidgetTester tester) async {
      // App starts in the first device locale if the device locale is
      // supported and there is no locale saved in shared preferences
      tester.platformDispatcher.localesTestValue = supportedLocalesList;
      expect(tester.platformDispatcher.locales, supportedLocalesList);

      // Build the AppView widget with the mocked settings repository
      await tester.pumpWidget(
        App(settingsRepository: mockSettingsRepository),
      );
      await tester.pumpAndSettle();
      debugDumpApp();

      // Verify result
      final context = tester.element(find.byType(HomePage));
      expect(Localizations.localeOf(context), supportedLocalesList.first);
    });
  });
}

```

</details>


### Screenshots or Video

<details>
<summary>Screenshots / Video demonstration</summary>

[Upload media here]

</details>


### Logs

<details><summary>Logs</summary>

```console
AutomatedTestWidgetsFlutterBinding - DEBUG MODE
[root](renderObject: RenderView#44f06)
└View-[GlobalObjectKey TestFlutterView#9c6fe]
└_ViewScope
└_MediaQueryFromView(state: _MediaQueryFromViewState#044ed)
└MediaQuery(MediaQueryData(size: Size(800.0, 600.0), devicePixelRatio: 3.0, textScaleFactor: 1.0, platformBrightness: Brightness.light, padding: EdgeInsets.zero, viewPadding: EdgeInsets.zero, viewInsets: EdgeInsets.zero, systemGestureInsets: EdgeInsets.zero, alwaysUse24HourFormat: false, accessibleNavigation: false, highContrast: false, disableAnimations: false, invertColors: false, boldText: false, navigationMode: traditional, gestureSettings: DeviceGestureSettings(touchSlop: null), displayFeatures: []))
└App
└RepositoryProvider<SettingsRepository>(value: MockSettingsRepository)
└_InheritedProviderScope<SettingsRepository?>
└BlocProvider<LocaleSettingsBloc>
└InheritedProvider<LocaleSettingsBloc>(value: Instance of 'LocaleSettingsBloc', listening to value)
└_InheritedProviderScope<LocaleSettingsBloc?>(value: Instance of 'LocaleSettingsBloc', listening to value)
└AppView(state: _AppViewState#a9e70)
└BlocBuilder<LocaleSettingsBloc, LocaleSettingsState>(dependencies: [_InheritedProviderScope<LocaleSettingsBloc?>], state: _BlocBuilderBaseState<LocaleSettingsBloc, LocaleSettingsState>#19932)
└BlocListener<LocaleSettingsBloc, LocaleSettingsState>(state: _BlocListenerBaseState<LocaleSettingsBloc, LocaleSettingsState>#83cb9)        
└MaterialApp(state: _MaterialAppState#82029)
└ScrollConfiguration(behavior: MaterialScrollBehavior)
└HeroControllerScope
└Focus(state: _FocusState#d0984)
└_FocusInheritedScope
└Semantics(container: false, properties: SemanticsProperties, tooltip: null, renderObject: RenderSemanticsAnnotations#f2fd8)
└WidgetsApp-[GlobalObjectKey _MaterialAppState#82029](state: _WidgetsAppState#3fe41)
└RootRestorationScope(state: _RootRestorationScopeState#4c17c)
└UnmanagedRestorationScope
└RestorationScope(dependencies: [UnmanagedRestorationScope], state: _RestorationScopeState#8d2bd)
└UnmanagedRestorationScope
└SharedAppData(state: _SharedAppDataState#47e80)
└_SharedAppModel
└Shortcuts(shortcuts: <Default WidgetsApp Shortcuts>, state: _ShortcutsState#5ab9f)
└Focus(debugLabel: "Shortcuts", dependencies: [_FocusInheritedScope], state: _FocusState#0db38)
└_FocusInheritedScope
└Semantics(container: false, properties: SemanticsProperties, tooltip: null, renderObject: RenderSemanticsAnnotations#e4a44)
└DefaultTextEditingShortcuts
└Shortcuts(shortcuts: <Default Text Editing Shortcuts>, state: _ShortcutsState#4d2c5)
└Focus(debugLabel: "Shortcuts", dependencies: [_FocusInheritedScope], state: _FocusState#8d58a)
└_FocusInheritedScope
└Semantics(container: false, properties: SemanticsProperties, tooltip: null, renderObject: RenderSemanticsAnnotations#b1fc5)
└Actions(dispatcher: null, actions: {DoNothingIntent: DoNothingAction#6ac15, DoNothingAndStopPropagationIntent: DoNothingAction#9e2e8, RequestFocusIntent: RequestFocusAction#72b81, NextFocusIntent: NextFocusAction#c1802, PreviousFocusIntent: PreviousFocusAction#bec27, DirectionalFocusIntent: DirectionalFocusAction#2ab71, ScrollIntent: _OverridableContextAction<ScrollIntent>#cb939(defaultAction: ScrollAction#87e7f), PrioritizedIntents: PrioritizedAction#84877, VoidCallbackIntent: VoidCallbackAction#dbd5b}, state: _ActionsState#c0ef4)
└_ActionsScope
└FocusTraversalGroup(policy: ReadingOrderTraversalPolicy#1d905, state: _FocusTraversalGroupState#8772f)
└Focus(debugLabel: "FocusTraversalGroup", focusNode: _FocusTraversalGroupNode#5eba6(FocusTraversalGroup), dependencies: [_FocusInheritedScope], state: _FocusState#c0ccb)
└_FocusInheritedScope
└TapRegionSurface(renderObject: RenderTapRegionSurface#08b56)
└ShortcutRegistrar(state: _ShortcutRegistrarState#2116a)
└_ShortcutRegistrarScope
└Shortcuts(manager: ShortcutManager#34d54(shortcuts: {}), shortcuts: {}, state: _ShortcutsState#7c82e)       
└Focus(debugLabel: "Shortcuts", dependencies: [_FocusInheritedScope], state: _FocusState#f3df2)
└_FocusInheritedScope
└Semantics(container: false, properties: SemanticsProperties, tooltip: null, renderObject: RenderSemanticsAnnotations#c4c5b)
└Localizations(locale: ar, delegates: [_AppLocalizationsDelegate[AppLocalizations], GlobalMaterialLocalizations.delegate(79 locales), GlobalCupertinoLocalizations.delegate(78 locales), GlobalWidgetsLocalizations.delegate(79 locales), LocaleNamesLocalizationsDelegate[LocaleNames], DefaultMaterialLocalizations.delegate(en_US), DefaultCupertinoLocalizations.delegate(en_US), DefaultWidgetsLocalizations.delegate(en_US)], state: _LocalizationsState#28eae)
└SizedBox.shrink(renderObject: RenderConstrainedBox#68818)
```

</details>


### Flutter Doctor output

<details><summary>Doctor output</summary>

```console
Doctor summary (to see all details, run flutter doctor -v):
[√] Flutter (Channel stable, 3.13.4, on Microsoft Windows [Version 10.0.19045.3324], locale en-GB)
[√] Windows Version (Installed version of Windows is version 10 or higher)
[√] Android toolchain - develop for Android devices (Android SDK version 33.0.0)
[√] Visual Studio - develop Windows apps (Visual Studio Community 2022 17.3.3)
[√] Android Studio (version 2022.3)
[√] Connected device (1 available)
[√] Network resources

• No issues found!
```

</details>