Closed VytorCalixto closed 4 years ago
I've just spent two hours configuring all the required things, but I've made the following approach:
String safeTranslate(String key)
).safeTranslate(key)
every time I need a translationExample:
TranslateService
I use get_it
and injectable
as a service locator in my app.
import 'package:flutter_translate/flutter_translate.dart' as globalTranslate;
import 'package:injectable/injectable.dart';
/// Implementation that is registered in GetIt service locator
@RegisterAs(TranslateService)
@injectable
class TranslateServiceImpl implements TranslateService {
@override
String safeTranslate(String key) {
try{
return globalTranslate.translate(key);
} catch(Exception){
return "translation.error";
}
}
}
/// Abstract translate service
abstract class TranslateService {
String safeTranslate(String key);
}
At this point, you need to configure GetIt
- go through their tutorials on pages linked above and all should be safe and sound. Two notes that are not mentioned in tutorials:
test/**
source folder in build.yaml
flutter packages pub run build_runner watch test
once configured to generate test dependenciesimport 'package:get_it/get_it.dart';
...
/// Class that will be tested
class TestedClass {
/// Instance of TranslateService that is provided by GetIt (service locator)
final TranslateService _translateService = GetIt.instance.get();
// Some method that uses translation
String doSomeStuff() {
return _translateService.safeTranslate("translation_key")
}
}
your_class_test.dart
file under test
folder
/// Important: GetIt needs to be initialized in a top level function
@injectableInit
void configureInjection(String environment) =>
$initGetIt(GetIt.instance, environment: environment);
void main() {
configureInjection("Some env value");
FlutterTest.test("Date formatter: today date", (){ /// Translation service should be located once class is created final TestedClass testedClass = TestedClass(); String safeTranslation = testedClass.doSomeStuff(); <--- no exception here ... });
@VytorCalixto you can call Localization.load(<String,dynamic>{});
before tests and error won't be thrown
When testing a widget the
_translations
map is passed as null and throws a exception. It's possible to wrap the widget in aLocalizedApp
widget and configure the localization, but I believe that testing a single widget should be more straightforward. Am I missing something here?Example error: