easy_localization
easy_localization copied to clipboard
Widget using Plural unable to be tested
I am unable to run widget tests for a widget that uses the plural extension method.
The tests are failing with the following error
══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
The following LateError was thrown building _OpenWorkCount(dirty):
LateInitializationError: Field '_locale@2908425997' has not been initialized.
...
When the exception was thrown, this was the stack:
#0 Localization._locale (package:easy_localization/src/localization.dart)
#1 Localization.plural (package:easy_localization/src/localization.dart:152:36)
#2 plural (package:easy_localization/src/public.dart:114:31)
#3 StringTranslateExtension.plural (package:easy_localization/src/public_ext.dart:104:10)
...
When I change the widget to use just a standard translation with the .tr extension method the tests pass.
Any help on how to set up my tests so that the locale gets initialised would be great.
Right now I am doing the following in my tests.
void main() async {
testWidgets('Test', (tester) async {
TestWidgetsFlutterBinding.ensureInitialized();
SharedPreferences.setMockInitialValues({});
EasyLocalization.logger.enableBuildModes = [];
await EasyLocalization.ensureInitialized();
await tester.pumpWidget(
EasyLocalization(
path: 'assets/translations',
supportedLocales: const [
Locale('en', 'US'),
],
child: MaterialApp(
home: WigetUnderTest(),
),
),
);
});
}
Am currently working around this by calling the following block in a setUpAll in my widget tests.
import 'package:easy_localization/easy_localization.dart';
import 'package:easy_localization/src/easy_localization_controller.dart';
import 'package:easy_localization/src/localization.dart';
import 'package:flutter/material.dart';
Future<void> initEasyLocalization(Locale locale) async {
final localizationController = EasyLocalizationController(
forceLocale: locale,
fallbackLocale: locale,
supportedLocales: [locale],
path: 'assets/translations',
useOnlyLangCode: false,
useFallbackTranslations: false,
onLoadError: (FlutterError e) {},
saveLocale: true,
assetLoader: const RootBundleAssetLoader(),
);
await localizationController.loadTranslations();
Localization.load(
locale,
translations: localizationController.translations,
);
}