I'm trying to use getX as flutter state management tool. GetX has its way handling language translation. One thing that I'm not sure is how could I initialise translation source from a remote server instead of hard code the translations. In such a way, I have the benefit of modifying translation without the need to release a new app.
Any suggest are welcome. Thanks.
I have DotNet WebAPI backend and I am sending translations like the following format:
[ApiController]
[Route("[controller]")]
public class TranslationsController : ControllerBase
{
[HttpGet]
public async Task<IActionResult> GetAll()
{
return Ok(new
{
en_US = new
{
hi = "Hi",
bye = "Bye"
},
bn_BD = new
{
hi = "ওহে",
bye = "বিদায়"
}
});
}
}
And my AppTranslations class:
class AppTranslations extends Translations {
final Map<String, String> en_US;
final Map<String, String> bn_BD;
AppTranslations({required this.en_US, required this.bn_BD});
static AppTranslations fromJson(dynamic json) {
return AppTranslations(
en_US: Map<String, String>.from(json["en_US"]),
bn_BD: Map<String, String>.from(json["bn_BD"]),
);
}
@override
Map<String, Map<String, String>> get keys => {
"en_US": en_US,
"bn_BD": bn_BD,
};
}
My TranslationProvider:
class TranslationProvider extends GetConnect {
Future<AppTranslations?> getTranslations() async {
final url = 'http://192.168.0.106:5000/translations';
final response = await get(url, decoder: AppTranslations.fromJson);
if (response.hasError) {
return Future.error(response.statusText!);
}
return response.body;
}
}
Then in my main function:
void main() async {
final translationProvider = TranslationProvider();
final translations = await translationProvider.getTranslations();
runApp(MyApp(translations: translations!));
}
And here's my MyApp:
class MyApp extends StatelessWidget {
final AppTranslations translations;
const MyApp({Key? key, required this.translations}) : super(key: key);
@override
Widget build(BuildContext context) {
return GetMaterialApp(
translations: translations,
locale: Locale("en_US"),
home: MyHomePage(),
);
}
}
And you are done! Now you can update your translations in the API and the update will reflect on the app.