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

Flutter:利用EasyLocalizations监听应用内Locale变化并触发请求

解决EasyLocalizations应用内Locale变化时触发数据刷新的问题

系统级的WidgetsBindingObserver和PlatformDispatcher.instance.onLocaleChanged仅监听系统语言切换,对EasyLocalizations通过context.setLocale实现的应用内语言切换无效。结合Provider状态管理,可通过以下方式实现Locale变化时自动请求数据:

方法一:在StatefulWidget中监听Locale变化

利用didChangeDependencies生命周期方法,对比前后Locale值,变化时触发Provider的数据请求:

class YourPage extends StatefulWidget {
  @override
  State<YourPage> createState() => _YourPageState();
}

class _YourPageState extends State<YourPage> {
  Locale? _lastLocale;

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    final currentLocale = EasyLocalizations.of(context).locale;
    if (_lastLocale != currentLocale) {
      // 调用Provider的方法请求对应语言的数据
      context.read<DataProvider>().fetchLocalizedData(currentLocale);
      _lastLocale = currentLocale;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // 页面内容
    );
  }
}

方法二:订阅EasyLocalizations的Locale变化监听

直接给EasyLocalizations实例添加监听器,Locale变更时触发数据请求:

class YourPage extends StatefulWidget {
  @override
  State<YourPage> createState() => _YourPageState();
}

class _YourPageState extends State<YourPage> {
  late EasyLocalizations _easyLocalizations;

  @override
  void initState() {
    super.initState();
    _easyLocalizations = EasyLocalizations.of(context);
    _easyLocalizations.addListener(_handleLocaleChange);
  }

  @override
  void dispose() {
    _easyLocalizations.removeListener(_handleLocaleChange);
    super.dispose();
  }

  void _handleLocaleChange() {
    final newLocale = _easyLocalizations.locale;
    context.read<DataProvider>().fetchLocalizedData(newLocale);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // 页面内容
    );
  }
}

Provider中的数据请求实现

在Provider类中实现根据Locale请求数据的方法:

class DataProvider extends ChangeNotifier {
  List<dynamic> _localizedData = [];

  List<dynamic> get localizedData => _localizedData;

  Future<void> fetchLocalizedData(Locale locale) async {
    // 根据Locale构造请求参数,比如用languageCode
    final response = await http.get(
      Uri.parse('https://your-api-endpoint.com/data?lang=${locale.languageCode}'),
    );
    
    if (response.statusCode == 200) {
      _localizedData = json.decode(response.body);
      notifyListeners();
    }
    // 可添加错误处理逻辑
  }
}

注意事项

  • 确保页面上下文已被EasyLocalizations包裹(即MaterialApp在EasyLocalizations内部)
  • 使用context.read<DataProvider>()而非watch,避免因Provider状态变化导致页面不必要重建
  • 可添加防抖逻辑,防止频繁切换Locale时重复发起请求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 15:32:18