Setting locale in flutter integration test using integration_test package

Viewed 653

I'm trying to put together a test using the integration_test package that sets a particular locale before running the test. I tried the following (which is close to what works in WidgetTests):

    await tester.binding.setLocale('en', 'US');
    app.main();
    await tester.idle();
    await tester.pumpAndSettle();

    // The app is still using the default locale of the phone...

Does this need to be set in the driver? Here's my current setup in the driver:

  // Some adb commands for granting permissions...
  print('Starting test.');
  final FlutterDriver driver = await FlutterDriver.connect();
  final String data = await driver.requestData(
    null,
    timeout: const Duration(minutes: 1),
  );
  await driver.close();
  // Some more adb commands to revoke permissions.

That doesn't seem to work.

I found this issue here, but it's not using the integration_test package and thus has a different setup altogether.

1 Answers

I was able to localize my integration tests by wrapping my target widget in the Localizations widget. Something like:

class WidgetTestWrapper extends StatelessWidget {
  const WidgetTestWrapper({
    Key? key,
    required this.locale,
    required this.child,
  }) : super(key: key);

  final Widget child;
  final Locale locale;

  static const localizationsDelegates = <LocalizationsDelegate>[
    S.delegate,
    GlobalMaterialLocalizations.delegate,
    GlobalWidgetsLocalizations.delegate,
    GlobalCupertinoLocalizations.delegate,
  ];

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Material(
        child: Localizations(
          locale: locale,
          delegates: localizationsDelegates,
          child: child,
        ),
      ),
    );
  }
}

Then I pass in the desired Locale for the test in the call to runApp.

For example, for Spanish US (es-US):

runApp(WidgetTestWrapper(locale: const Locale('es', 'US'), child: widgetUnderTest));
Related