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

Flutter日历墨西哥西班牙语本地化报错求助

解决Flutter日历本地化墨西哥西班牙语时的MaterialLocalization缺失问题

问题原因

你的代码中嵌套了两个MaterialApp组件,每个MaterialApp会创建独立的本地化上下文环境,导致DatePickerDialog无法找到所需的MaterialLocalizations实例,触发报错。

解决方案

1. 统一本地化配置到根MaterialApp

移除ChildWidget中的MaterialApp,只保留根组件的MaterialApp,将本地化相关配置集中在这里:

class MyHomePage extends StatefulWidget {
  ...
}

class _MyHomePageState extends State<MyHomePage> {
  ...
  @override
  Widget build(BuildContext context) {
    ...
    return MaterialApp(
      localizationsDelegates: [
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
      ],
      supportedLocales: [
        const Locale('en'),
        const Locale('es', 'MX'),
      ],
      locale: const Locale('es', 'MX'),
      home: ChildWidget(),
    );   
  }
}

// ChildWidget 改为普通组件,不再返回MaterialApp
class ChildWidget extends StatefulWidget {
  ...
}

class _ChildWidgetState extends State<ChildWidget> {
  ...
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('示例页面')),
      body: Center(
        child: ElevatedButton(
          onPressed: () async {
            await showDatePicker(
              context: context,
              initialDate: DateTime.now(),
              firstDate: DateTime(2020),
              lastDate: DateTime(2030),
            );
          },
          child: Text('打开日历选择器'),
        ),
      ),
    );
  }
}

2. 确保使用正确的上下文

调用showDatePicker时,必须传入根MaterialApp子组件的上下文,避免使用MaterialApp外部的context,这样才能正确关联到本地化配置。

内容的提问来源于stack exchange,提问作者Group of Stars

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 01:41:01