Add localization to Widget without using MaterialApp?

Viewed 456

I understand how to add localization to an app by adding localizationsDelegates and supportedLocales to the MaterialApp widget. Localizing my app is working fine.

I'm creating a Flutter package that can be used within other Flutter apps. Some of the widgets within the package need to have localized text, like some of the error messages and button labels. The package contains all of its own localized strings. How can I localize the strings in my package without MaterialApp?

1 Answers

I've used Localizations widget in this way for testing without using a MaterialApp:

A simple demo widget:

class WidgetToTest extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    //AppLocalizations.of(context)!.hello = 'hello' in generated file
    return Text(AppLocalizations.of(context)!.hello);
  }
}

The test:

  testWidgets('test localizations widget', (tester) async {
    await tester.pumpWidget(
      Localizations(
        locale: const Locale('en'),
        delegates: AppLocalizations.localizationsDelegates,
        child: WidgetToTest(),
      )
    );
    expect(find.text('hello'), findsOneWidget);
  });

You can use Localizations widget if you just need to enable AppLocalizations to work inside your widgets.

Related