1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Flutter] update font family based on selected language

Discussão em 'Mobile' iniciado por Stack, Outubro 7, 2024 às 01:32.

  1. Stack

    Stack Membro Participativo

    Using Flutter and Getx .. i want to update the font family based on selected language .. so if i select english language the font family updated to "Poppins" .. if it arabic the font updated to "Cairo" .. i tried this in controller and the font family changed but the theme did not updated

    main.dart


    void main() async {
    WidgetsFlutterBinding.ensureInitialized();
    await initialServices();
    LanguageController controller = Get.put(LanguageController());
    runApp(
    GetMaterialApp(
    themeMode: ThemeMode.light,
    theme: AppTheme.lightTheme,
    darkTheme: AppTheme.darkTheme,
    getPages: AppPages.routes,
    initialRoute: AppPages.INITIAL,
    translations: AppTranslation(),
    locale: controller.initLang,

    ),
    );
    }


    and the app theme class

    class AppTheme {
    AppTheme._();

    static ThemeData lightTheme = _buildLightTheme();
    static ThemeData darkTheme = _buildDarkTheme();

    // ---------------- LIGHT THEME ---------------- //
    static ThemeData _buildLightTheme() {
    return ThemeData(
    fontFamily: 'Cairo',
    brightness: Brightness.light,
    );
    }

    // ---------------- DARK THEME ---------------- //
    static ThemeData _buildDarkTheme() {
    return ThemeData(
    fontFamily: 'Cairo',
    brightness: Brightness.dark,
    );
    }
    }

    LanguageController.dart


    class LanguageController extends GetxController {
    Locale? initLang;

    AppServices appServices = Get.find();

    changeLang(String languageCode) {
    Locale locale = Locale(languageCode);
    appServices.box.write(AppStorageKeys.lang, languageCode);
    Get.updateLocale(locale);
    }

    @override
    void onInit() {
    String? storedLang = appServices.box.read(AppStorageKeys.lang);
    initLang = _getLocaleFromStoredLang(storedLang) ?? _getDefaultLocale();
    super.onInit();
    }

    /// Get the stored language if it exist
    Locale? _getLocaleFromStoredLang(String? storedLang) {
    return storedLang != null ? Locale(storedLang) : null;
    }

    /// Get the default device language
    Locale _getDefaultLocale() {
    return Locale(Get.deviceLocale!.languageCode);
    }
    }

    Continue reading...

Compartilhe esta Página