In flutter string text are directly set to the TextField
widget like:
new Text(\'Hello, How are you?\')
Is correct way ? or we ca
For those of you who don't want to use any 3rd party plugin, here is how you can do it.
Create a folder strings
in assets
. Put your language file in it.
assets
strings
- en.json // for english
- ru.json // for russian
Now in en.json
, write your string, for example.
{
"text1": "Hello",
"text2": "World"
}
Similarly, in ru.json
,
{
"text1": "Привет",
"text2": "Мир"
}
Add this to pubspec.yaml
file (mind the spaces)
flutter:
uses-material-design: true
assets:
- assets/strings/en.json
- assets/strings/ru.json
Now you are all set to use these strings in your app. Here is the sample code, the AppBar
shows the translated text.
void main() {
runApp(
MaterialApp(
locale: Locale("ru"), // switch between en and ru to see effect
localizationsDelegates: [const DemoLocalizationsDelegate()],
supportedLocales: [const Locale('en', ''), const Locale('ru', '')],
home: HomePage(),
),
);
}
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text(DemoLocalizations.of(context).getText("text2") ?? "Error")),
);
}
}
// this class is used for localizations
class DemoLocalizations {
static DemoLocalizations of(BuildContext context) {
return Localizations.of(context, DemoLocalizations);
}
String getText(String key) => language[key];
}
Map language;
class DemoLocalizationsDelegate extends LocalizationsDelegate {
const DemoLocalizationsDelegate();
@override
bool isSupported(Locale locale) => ['en', 'ru'].contains(locale.languageCode);
@override
Future load(Locale locale) async {
String string = await rootBundle.loadString("assets/strings/${locale.languageCode}.json");
language = json.decode(string);
return SynchronousFuture(DemoLocalizations());
}
@override
bool shouldReload(DemoLocalizationsDelegate old) => false;
}