Skip to content

Instantly share code, notes, and snippets.

@oligazar
Created April 10, 2020 07:15
Show Gist options
  • Save oligazar/1bdb8514087902cfa84849b3ffbd5265 to your computer and use it in GitHub Desktop.
Save oligazar/1bdb8514087902cfa84849b3ffbd5265 to your computer and use it in GitHub Desktop.
class TestLocalizationsDelegate
extends LocalizationsDelegate<TestLocalizations> {
const TestLocalizationsDelegate();
@override
bool isSupported(Locale locale) {
return [DE, EN, PL].contains(locale.languageCode);
}
@override
Future<TestLocalizations> load(Locale locale) {
return TestLocalizations.load(locale);
}
@override
bool shouldReload(LocalizationsDelegate<TestLocalizations> old) => false;
}
class TestLocalizations {
static Future<TestLocalizations> load(Locale locale) async {
final String localeName =
locale.countryCode == null || locale.countryCode.isEmpty
? locale.languageCode
: locale.toString();
final String canonicalLocaleName = Intl.canonicalizedLocale(localeName);
print("localName: $localeName");
print("canonicalLocaleName: $canonicalLocaleName");
await initializeMessages(canonicalLocaleName);
return TestLocalizations();
}
static TestLocalizations of(BuildContext context) {
return Localizations.of<TestLocalizations>(
context, TestLocalizations);
}
String get title => Intl.message('Test title', name: 'title');
String get message => Intl.message('Test message', name: 'message');
}
class MyTestWidget extends StatelessWidget {
final String title;
final String message;
const MyTestWidget({
Key key,
@required this.title,
@required this.message,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: "My Test App",
home: Scaffold(
appBar: AppBar(
title: Text(title),
),
body: Center(
child: Text(message),
),
),
);
}
}
void main() {
Widget withLocalizations({Widget child}) => Localizations(
child: child,
locale: Locale(EN),
delegates: [
const TestLocalizationsDelegate(),
GlobalWidgetsLocalizations.delegate,
],
);
testWidgets("Localizations", (WidgetTester tester) async {
// runAsync is not necessary in this case
await tester.runAsync(() async {
String title = "T", message = "M";
await tester.pumpWidget(withLocalizations(child: Builder(
builder: (context) {
final loc = TestLocalizations.of(context);
title = loc.title;
message = loc.message;
return MyTestWidget(title: title, message: message);
},
))); // localizationsWrap(
await tester.pumpAndSettle();
final titleFinder = find.text(title);
final messageFinder = find.text(message);
expect(titleFinder, findsOneWidget);
expect(messageFinder, findsOneWidget);
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment