Search code examples
flutterflutter-test

Flutter widget test EasyLocalization is enable to initialize


I m trying the simplest test has possible and when I ensureInitialized EasyLocalization the test never stops.

If I don't ensureInitialized EasyLocalization the test crash with The following LateError was thrown attaching to the render tree: LateInitializationError: Field '_deviceLocale@1348168148' has not been initialized.

My code

void main() {
  testWidgets('Should login', (WidgetTester tester) async {
    await initAppWidgetTest(tester);
    expect(find.byType(ElevatedButton), findsOneWidget);
  });
}

Future<void> initAppWidgetTest(WidgetTester tester) async {
  TestWidgetsFlutterBinding.ensureInitialized();
  await EasyLocalization.ensureInitialized();
  getIt.registerSingleton<AppRouter>(
    AppRouter(
      checkIfAuthenticated: CheckIfAuthenticated(),
    ),
  );
  await tester.pumpWidget(initApp());
  await tester.pumpAndSettle();
  await tester.pump(const Duration(seconds: 2));
}

Widget initApp() {
  return EasyLocalization(
    supportedLocales: const [Locale('fr', 'FR'), Locale('en', 'EN')],
    path: './assets/languages',
    fallbackLocale: const Locale('fr', 'FR'),
    assetLoader: const CodegenLoader(),
    child: MultiProvider(
      providers: [
        ChangeNotifierProvider(
          create: (_) => CompanyInfosProvider(),
        ),
        ChangeNotifierProvider(
          create: (_) => SitesInfosProvider(),
        ),
      ],
      child: MyApp(),
    ),
  );
}

Solution

  • I was only missing this line that need to be done before

    WidgetsFlutterBinding.ensureInitialized();
    

    My understanding of this is that EasyLocalization is not runned in TestWidgetsFlutterBinding and need a real app initialization