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

如何通过flutter_localization动态翻译ThemeMode名称?

解决Flutter中ThemeMode动态本地化翻译的问题

Dart不支持AppLocale.${e.name}这种动态访问类静态成员的写法,你可以通过以下两种方案实现ThemeMode的动态本地化翻译:

方案一:使用枚举扩展(推荐)

通过扩展ThemeMode枚举,为每个枚举值绑定对应的本地化字符串获取逻辑,代码更易维护且类型安全:

extension ThemeModeLocalization on ThemeMode {
  String getLocalizedString(BuildContext context) {
    switch (this) {
      case ThemeMode.system:
        return AppLocale.systemMode.getString(context);
      case ThemeMode.light:
        return AppLocale.lightMode.getString(context);
      case ThemeMode.dark:
        return AppLocale.darkMode.getString(context);
    }
  }
}

之后在按钮中直接调用扩展方法即可:

Text(e.getLocalizedString(context))

方案二:使用映射表

创建ThemeMode到本地化key的映射,再通过key获取对应翻译字符串:

// 定义映射关系
const themeModeToKey = {
  ThemeMode.system: 'system_mode',
  ThemeMode.light: 'light_mode',
  ThemeMode.dark: 'dark_mode',
};

然后在代码中使用:

// 假设你的本地化库支持通过key获取字符串,根据实际API调整
Text(AppLocale.getString(context, themeModeToKey[e]!))

修改后的完整代码示例(使用扩展方案)

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:myapp/localization.dart';
import 'package:myapp/shared_preferences.dart';

import 'common.dart';

extension ThemeModeLocalization on ThemeMode {
  String getLocalizedString(BuildContext context) {
    switch (this) {
      case ThemeMode.system:
        return AppLocale.systemMode.getString(context);
      case ThemeMode.light:
        return AppLocale.lightMode.getString(context);
      case ThemeMode.dark:
        return AppLocale.darkMode.getString(context);
    }
  }
}

class ThemeModeList extends ConsumerStatefulWidget {
  const ThemeModeList({super.key});

  @override
  ConsumerState<ThemeModeList> createState() => _ThemeModeList();
}

class _ThemeModeList extends ConsumerState<ThemeModeList> {
  late ThemeMode themeMode;

  @override
  Widget build(BuildContext context) {
    themeMode = ref.watch(themeModeProvider);
    return Container(
      child: Column(
        children: ThemeMode.values
            .map((e) => ElevatedButton(
                  child: Text(e.getLocalizedString(context)),
                  onPressed: () async {
                    final themeModeNotifier =
                        ref.read(themeModeProvider.notifier);
                    themeModeNotifier.update(e);
                    Navigator.of(context).pop();
                    // 无需setState,Riverpod会自动监听状态变化更新UI
                  },
                ))
            .toList(),
      ),
    );
  }
}

注意事项

  • 确保你的本地化文件(localization.dart)中已定义好对应静态成员(如systemMode、lightMode、darkMode)及各语言的翻译文本。
  • 原代码中的setState可以移除,因为Riverpod的watch会自动监听状态变化并重建UI。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 16:32:50