We can resolve this by using [get_it][1] easily, we can use the string anywhere after this setup.
1. Install this to your vscode [Flutter Intl VSCode Extension](
[To see links please register here]
)
2. setup `pubspec.yaml`
```
dependencies:
flutter:
sdk: flutter
flutter_localizations: # Add this line
sdk: flutter # Add this line
intl: ^0.17.0 # Add this line
get_it: ^7.2.0 # Add this line
flutter:
uses-material-design: true
generate: true # Add this line
flutter_intl: # Add this line
enabled: true # Add this line
class_name: I10n # Add this line
main_locale: en # Add this line
arb_dir: lib/core/localization/l10n # Add this line
output_dir: lib/core/localization/generated # Add this line
```
3. Setup `main.dart`
```
import 'package:component_gallery/core/localization/generated/l10n.dart';
import 'package:component_gallery/locator.dart';
import 'package:component_gallery/ui/pages/home.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
void main() {
setupLocator();
runApp(App());
}
class App extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
localizationsDelegates: [
I10n.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
supportedLocales: I10n.delegate.supportedLocales,
localeResolutionCallback: (deviceLocale, supportedLocales) {
if (supportedLocales
.map((e) => e.languageCode)
.contains(deviceLocale?.languageCode)) {
return deviceLocale;
} else {
return const Locale('en', '');
}
},
home: HomePage(),
);
}
}
```
4. setup `locator.dart`
```
import 'package:component_gallery/core/services/navigation_service.dart';
import 'package:get_it/get_it.dart';
GetIt locator = GetIt.instance;
void setupLocator() {
locator.registerLazySingleton(() => I10n());
}
```
5. Use it with Get_it without context as
```
final I10n _i10n = locator<I10n>();
class MessageComponent extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Text(
_i10n.sample,
textAlign: TextAlign.center,
);
}
}
```
[1]:
[To see links please register here]