easy_localization have fallback values for keys on other languages - flutter

When working with this package for localization, and base translation done in EN, I want my 2nd language to show keys if they are present in 2nd language json file, but if they are not, to consume en.json equivalent value. Issue is that by default this package shows key that doesn't exist in JSON file, instead of fallback translation file value. Is there a way to override this?
Usage of the plugin in main.dart file
runApp(
EasyLocalization(
child: MyApp(),
useOnlyLangCode: true,
fallbackLocale: Locale('en'),
supportedLocales: [
Locale('en'),
Locale('es'),
],
path: 'lang',
),
);
And when I want to translate a key that exists in en.json, but doesn't exist in es.json file it looks like this:
tr('appTitle');
Expected result would be "Hello world", but I get "appTitle" on the screen.

Old question, but since I just ran into the same problem:
There is now(?) a parameter "useFallbackTranslations" that you have to set to true. Indeed a bit counterintuitive, because one would assume that setting fallbackLocale should be enough.
EasyLocalization(
fallbackLocale: const Locale('en'),
supportedLocales: const [
Locale('en'),
Locale('es'),
Locale('de'),
],
useOnlyLangCode: true,
useFallbackTranslations: true, // <------
path: 'assets/i18n',
child: const MyApp(),
))

This is the EasyLocalization settings in runApp:
runApp(
EasyLocalization(
useOnlyLangCode: true,
useFallbackTranslations: true,
path: LanguageManager.langAssetPath,
supportedLocales: LanguageManager.instance.supportedLocales,
startLocale: LanguageManager.instance.dlLocale,
fallbackLocale: LanguageManager.instance.dlLocale,
child: const App(),
),
);
And the separated LanguageManager class
class LanguageManager {
LanguageManager._init();
static LanguageManager get instance => _instance ??= LanguageManager._init();
static LanguageManager? _instance;
static const langAssetPath = 'assets/translations';
final dlLocale = const Locale('en', 'US'); // necessary
final enLocale = const Locale('en');
final trLocale = const Locale('tr');
List<Locale> get supportedLocales => [dlLocale, enLocale, trLocale];
// constants
static const supportedLanguages = ['en', 'tr'];
Locale getCurrentLocale() {
return supportedLanguages.contains(getCurrentLang)
? Locale(getCurrentLang)
: const Locale('en');
}
String get getCurrentLang => Platform.localeName.substring(0, 2);
}
Finally assets/translations folder must en-US.json, en.json and tr.json
Don't forget generating
PS: This solution is from Veli Bacik in Turkey

Related

couldn't create named routes in Flutter

I defined needed routes in Material App and everything works fine, bit I have to add another button which should lead to authorisation page and now I am getting this error:
The following assertion was thrown while handling a gesture:
Could not find a generator for route RouteSettings("/changeUsers", null) in the _WidgetsAppState.
Make sure your root app widget has provided a way to generate
this route.
Generators for routes are searched for in the following order:
1. For the "/" route, the "home" property, if non-null, is used.
2. Otherwise, the "routes" table is used, if it has an entry for the route.
3. Otherwise, onGenerateRoute is called. It should return a non-null value for any valid route not handled by "home" and "routes".
4. Finally if all else fails onUnknownRoute is called.
My code look like this:
return MaterialApp(
debugShowCheckedModeBanner: false,
initialRoute: '/',
routes: {
'/': (context) => const AuthorizationPage(),
'/adminLogin': (context) => const AuthInsertLogging(),
'/mainPageUsers': (context) => const TabBarBottomUsers(),
'/mainPageAdmin': (context) => const TabBarBottom(),
"/logout": (_) => new AuthorizationPage(),
'/changeUsers': (_) => AuthorizationPage(),
},
);
}
This is the button I tried to make route:
child: ElevatedButton(
onPressed: () {
Navigator.pushNamed(context, '/changeUsers');
},
child: Text(
'Change User',
style: GoogleFonts.montserrat(
color: Colors.white,
fontSize: 20,
fontWeight: FontWeight.w500,
letterSpacing: 2),
),
This is because you use the AuthorizationPage for '/' home, '/logout' and '/changeUsers' routes. There is a rule for routes property in Flutter documentation. See details here
If home is specified, then it implies an entry in this table for the
Navigator.defaultRouteName route ( here '/' ), and it is an error to
redundantly provide such a route in the routes table.
The rule says there must be only one home route ( here '/' route ) is specified. Here there are three routes pointing to same page.
So, just remove '/logout' and '/changeUers' routes and write onPressed function as follows.
Navigator.pushNamed(context, '/');

mixing rtl with ltr flutter text

my "(" ")" get flipped when I try to write text with Hebrew (rtl).
I look up in the internet but its don't work for me like:
locale: const Locale('he', 'IL'),
localizationsDelegates: const [
GlobalCupertinoLocalizations.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
],
supportedLocales: [
const Locale('he', 'IL'),
const Locale('en', '')
],
.
.
.
and:
return Directionality(textDirection: TextDirection.rtl, child: TabsScreen());
after a lot of test I find that the problem trigger when the phone settings is on English or another language but if the settings on Hebrew is work.
You can use the direction in text field to switch between rtl and ltr
Text(
direction : selectedLanguage == 'hebrew' ? TextDirection.rtl:TextDirection.ltr,
)

Flutter - How to force flutter_localizations to the desired lang?

I have integrated flutter localizations dependent of system language, works very well.
But I want to "force" language programmatically, without matters on system language.
My app root:
return GetMaterialApp(
localizationsDelegates: const [
AppLocalizations.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
supportedLocales: const [
Locale('sr', ''),
Locale('en', ''),
],
My lang config file:
arb-dir: lib/l10n
template-arb-file: app_sr.arb
output-localization-file: app_localizations.dart
Any every next new entering into the app will "keep" the user choose preferred language.
Thank you!
You can add the locale attribute to your MaterialApp, like that:
// Content from your MaterialApp
locale: const Locale('sr'),
// More content from your MaterialApp
If you need change in another part of your app, you can change de Locale in your AppLocalizations class.

flutter : how to rebuild all the qpp after change the current language

rebuild the app after do something like change the theme or change the current language , iam using the ( easy_localization: ^3.0.0 ) package to change the lang
EasyLocalization(
child: MyApp(currentMode: currentMode),
supportedLocales: const [
Locale('ar'),
Locale('en'),
],
path: 'assets/translations',
startLocale: const Locale('ar'),
assetLoader: const CodegenLoader(),
),
If you're looking for the solution to this problem, this one works perfectly(tested) !
Add the package phoenix from here
Wrap your main widget with Phoenix
void main() {
runApp(
Phoenix(
child: App(),
),
);
}
Call rebirth method anywhere in your app like so Phoenix.rebirth(context);
Or make use of state management solutions like riverpod.
You place your settings in a provider and watch it on the pages that should change when the state updates.

How to get argument from url in flutter web using get: ^3.26.0

return GetMaterialApp(
title: title,
theme: appTheme,
getPages: [
GetPage(name: '/', page: () => Splash()),
GetPage(name: '/update', page: () => Update()),
GetPage(name: '/login', page: () => SignIn()),
GetPage(name: '/reference', page: () => Reference()),
],
home: Splash(),
);
this is my route code and now i want to user enter url like : xyz.com/login/jayesh , then i want to get user name in login screen using getx state management.
In your route:
xyz.com/login?username=jayesh
And in your controller or in your view:
var username = Get.parameters["username"];
A good place to get your arguments or parameters may be in your controllers onInit or your views build method
add page with name in GetMaterialApp
getPages:[
GetPage(name: '/login/:refId', page: () => SignIn()),
],
you can retrive data(perameter) like:
var data = Get.parameters;
String id = data['refId'];