You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter应用如何根据用户使用的语言动态切换font family

Flutter 按应用当前语言动态切换字体族实现方案

你当前已配置的基础本地化代码如下:

localizationsDelegates: const [
  AppLocalizations.delegate,
  GlobalMaterialLocalizations.delegate,
  GlobalWidgetsLocalizations.delegate,
],
supportedLocales: const [
  Locale('en', ''),
  Locale('ar', ''),
],

具体实现步骤

1. 提前配置字体资源

先将不同语言对应的字体文件放入项目资源目录,在pubspec.yaml中完成字体注册,示例配置:

flutter:
  fonts:
    - family: Roboto # 英文默认字体
      fonts:
        - asset: assets/fonts/Roboto-Regular.ttf
        - asset: assets/fonts/Roboto-Bold.ttf
          weight: 700
    - family: Amiri # 阿拉伯语适配字体
      fonts:
        - asset: assets/fonts/Amiri-Regular.ttf
        - asset: assets/fonts/Amiri-Bold.ttf
          weight: 700

2. 新增语言与字体映射逻辑

定义全局存储当前生效Locale的变量,以及字体匹配方法:

// 存储当前应用生效的Locale
Locale? currentAppLocale;

// 根据语言代码返回对应字体族
String get matchedFontFamily {
  switch(currentAppLocale?.languageCode) {
    case 'ar':
      return 'Amiri';
    case 'en':
    default:
      return 'Roboto';
  }
}

3. 修改MaterialApp配置绑定动态字体

在原有本地化配置基础上新增localeResolutionCallback监听生效Locale,同时给全局Theme动态绑定字体:

MaterialApp(
  localizationsDelegates: const [
    AppLocalizations.delegate,
    GlobalMaterialLocalizations.delegate,
    GlobalWidgetsLocalizations.delegate,
  ],
  supportedLocales: const [
    Locale('en', ''),
    Locale('ar', ''),
  ],
  // 新增:监听当前生效的Locale
  localeResolutionCallback: (locale, supportedLocales) {
    if (locale != null) {
      for (var supportedLocale in supportedLocales) {
        if (supportedLocale.languageCode == locale.languageCode) {
          currentAppLocale = supportedLocale;
          return supportedLocale;
        }
      }
    }
    currentAppLocale = supportedLocales.first;
    return supportedLocales.first;
  },
  // 新增:全局主题动态绑定对应字体
  theme: ThemeData(
    fontFamily: matchedFontFamily,
    // 其余你的原有主题配置保留即可
  ),
  // 如果你有深色主题也同步配置fontFamily
  darkTheme: ThemeData(
    fontFamily: matchedFontFamily,
  ),
  home: const YourHomePage(),
)

可选优化:封装通用Text组件

如果部分页面需要自定义字体优先级,可以封装全局通用的Text组件自动适配字体,避免个别场景全局字体不生效的问题:

class AppText extends StatelessWidget {
  final String data;
  final TextStyle? style;
  // 其余Text的参数按需透传即可

  const AppText(this.data, {super.key, this.style});

  @override
  Widget build(BuildContext context) {
    // 直接从上下文获取当前Locale,无需全局存储变量
    final currentLocale = Localizations.localeOf(context);
    String fontFamily = currentLocale.languageCode == 'ar' ? 'Amiri' : 'Roboto';
    return Text(
      data,
      style: (style ?? const TextStyle()).copyWith(fontFamily: fontFamily),
    );
  }
}

使用时直接替换原有Text组件为AppText即可自动适配字体。


内容的提问来源于stack exchange,提问作者Mariam Albarghouti

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 15:15:01