Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the current locale in Flutter using the GetX package?

The example https://pub.dev/packages/get/example only shows setting the locale from a string manually:

void main() {
  runApp(GetMaterialApp(
    ...
    locale: Locale('pt', 'BR'),
    ...

If I don't use "locale: Locale ('pt', 'BR')", then code like Text("title".tr) don't work. So, I need setup current locale to "locale" property, but how get current locale?

like image 995
Sergey S. Avatar asked Aug 31 '20 11:08

Sergey S.


People also ask

Is GetX good for Flutter?

Obviously, both are used for state management. However, experienced Flutter devs do not recommend GetX. Do not use GetX.

What is locale in Flutter?

An identifier used to select a user's language and formatting preferences. This represents a Unicode Language Identifier (i.e. without Locale extensions), except variants are not supported. Locales are canonicalized according to the "preferred value" entries in the IANA Language Subtag Registry.


2 Answers

if BuildContext is available, we can get current locale this way

Locale myLocale = Localizations.localeOf(context);

according to the documentation https://flutter.dev/docs/development/accessibility-and-localization/internationalization

another option is to use the official intl library

import 'package:intl/intl.dart';

String locale = Intl.getCurrentLocale(); // returns language tag, such as en_US
like image 61
feedpanda Avatar answered Oct 18 '22 17:10

feedpanda


To get Device Current Locale:

import 'package:get/get.dart';

return GetMaterialApp(
     locale: Get.deviceLocale,   //returns Locale('<language code>', '<country code>')
);

To get the App Current Locale:

import 'package:get/get.dart';

return GetMaterialApp(
     locale: Get.locale,   //returns Locale('<language code>', '<country code>')
);

GetX | Flutter

Sample Code

like image 9
Zeeshan Ayaz Avatar answered Oct 18 '22 17:10

Zeeshan Ayaz