Skip to content

Instantly share code, notes, and snippets.

@eduardoflorence
Created March 3, 2021 01:36
Show Gist options
  • Save eduardoflorence/9503ca35950559618da71f55a74b6562 to your computer and use it in GitHub Desktop.
Save eduardoflorence/9503ca35950559618da71f55a74b6562 to your computer and use it in GitHub Desktop.
GetX - Sample Translation with GetStorage, GetxService, DropDownButton and PopMenuButton
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await initialConfig();
final storage = Get.find<StorageService>();
runApp(GetMaterialApp(
debugShowCheckedModeBanner: false,
translations: AppTranslations(),
// Get.deviceLocale with problem in iOS
// Not return countryCode, only return languageCode
// On the first load of the Application
// (flutter problem, not GetX)
locale: storage.languageCode != null
? Locale(storage.languageCode, storage.countryCode)
: Locale('pt', 'BR'), // Not Get.deviceLocale
fallbackLocale: Locale('en', 'US'),
initialRoute: '/home',
getPages: [GetPage(name: '/home', page: () => Home())],
initialBinding: InitialBinding(),
));
}
Future<void> initialConfig() async {
await Get.putAsync(() => StorageService().init());
// DBService, ...
}
class StorageService extends GetxService {
String languageCode;
String countryCode;
Future<StorageService> init() async {
await GetStorage.init();
languageCode = await GetStorage().read('languageCode');
countryCode = await GetStorage().read('countryCode');
return this;
}
void write(String key, dynamic value) {
GetStorage().write(key, value);
}
}
class Home extends StatelessWidget {
@override
Widget build(context) {
return Scaffold(
appBar: AppBar(
title: Text("${'hello'.tr}"),
actions: [LanguageMenu()],
),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Center(child: Text("${'welcome'.tr}")),
SizedBox(height: 32),
LanguageDropDown(),
],
),
);
}
}
class InitialBinding implements Bindings {
@override
void dependencies() {
Get.put(LanguageController(), permanent: true);
}
}
class LanguageController extends GetxController {
final storage = Get.find<StorageService>();
final RxString locale = Get.locale.toString().obs;
final Map<String, dynamic> optionsLocales = {
'en_US': {
'languageCode': 'en',
'countryCode': 'US',
'description': 'English'
},
'de_DE': {
'languageCode': 'de',
'countryCode': 'DE',
'description': 'German'
},
'pt_BR': {
'languageCode': 'pt',
'countryCode': 'BR',
'description': 'Português'
},
};
void updateLocale(String key) {
final String languageCode = optionsLocales[key]['languageCode'];
final String countryCode = optionsLocales[key]['countryCode'];
// Update App
Get.updateLocale(Locale(languageCode, countryCode));
// Update obs
locale.value = Get.locale.toString();
// Update storage
storage.write('languageCode', languageCode);
storage.write('countryCode', countryCode);
}
}
class LanguageDropDown extends GetView<LanguageController> {
@override
Widget build(BuildContext context) {
return Obx(
() => DropdownButton<String>(
value: controller.locale.value,
icon: Icon(Icons.arrow_downward),
iconSize: 24,
elevation: 16,
style: TextStyle(color: Colors.deepPurple),
underline: Container(
height: 2,
color: Colors.deepPurpleAccent,
),
onChanged: (String newValue) {
controller.updateLocale(newValue);
},
items: controller.optionsLocales.entries.map((item) {
return DropdownMenuItem<String>(
value: item.key,
child: Text(item.value['description']),
);
}).toList(),
),
);
}
}
class LanguageMenu extends GetView<LanguageController> {
@override
Widget build(BuildContext context) {
return PopupMenuButton(
icon: Icon(Icons.language),
offset: Offset(0, 30),
itemBuilder: (context) => controller.optionsLocales.entries.map((item) {
return PopupMenuItem(
value: item.key,
child: Text(item.value['description']),
);
}).toList(),
onSelected: (newValue) {
controller.updateLocale(newValue);
},
);
}
}
class AppTranslations extends Translations {
@override
Map<String, Map<String, String>> get keys => {
'en_US': {
'hello': 'Hello World',
'welcome': 'Welcome',
},
'de_DE': {
'hello': 'Hallo Welt',
'welcome': 'willkommen',
},
'pt_BR': {
'hello': 'Alo Mundo',
'welcome': 'Bem-vindo',
},
};
}
@kururu-abdo
Copy link

perfect

@tooinfinity
Copy link

I got a error in storage service languageCode and countryCode always return a null i fix it like this
languageCode = await GetStorage().read('languageCode') ?? 'en';
countryCode = await GetStorage().read('countryCode') ?? 'US';
but i think it's wrong

and error in LanguageDropDown onChange i fix it like this
onChanged: (String? newValue) {
controller.updateLocale(newValue!);
}
if this is a better solution let me know

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment