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

Flutter自定义to locale不被CupertinoLocalizations委托支持报错求助

解决自定义to语言Locale的CupertinoLocalizations警告问题

问题原因

你仅配置了Material风格的自定义本地化委托,但Cupertino(iOS风格)的本地化系统未找到支持to语言的对应委托,因此抛出警告。

解决步骤

1. 创建自定义Cupertino本地化实现

在你的to_intl.dart或单独新建文件中,实现CupertinoLocalizations抽象类:

import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';

class ToCupertinoLocalizations extends CupertinoLocalizations {
  ToCupertinoLocalizations(this.locale);

  final Locale locale;

  static ToCupertinoLocalizations of(BuildContext context) {
    return Localizations.of<ToCupertinoLocalizations>(context, ToCupertinoLocalizations)!;
  }

  static const LocalizationsDelegate<ToCupertinoLocalizations> delegate = _ToCupertinoLocalizationsDelegate();

  // 实现CupertinoLocalizations要求的所有方法,以下为示例
  @override
  String get alertDialogLabel => '提示';

  @override
  String get anteMeridiemAbbreviation => '上午';

  @override
  String get postMeridiemAbbreviation => '下午';

  // 需补充实现其他必填方法,如日期格式化、按钮文本等
}

class _ToCupertinoLocalizationsDelegate extends LocalizationsDelegate<ToCupertinoLocalizations> {
  const _ToCupertinoLocalizationsDelegate();

  @override
  bool isSupported(Locale locale) => locale.languageCode == 'to';

  @override
  Future<ToCupertinoLocalizations> load(Locale locale) {
    return SynchronousFuture<ToCupertinoLocalizations>(ToCupertinoLocalizations(locale));
  }

  @override
  bool shouldReload(_ToCupertinoLocalizationsDelegate old) => false;
}

2. 在main.dart中添加Cupertino本地化委托

更新localizationsDelegates列表,将自定义的Cupertino委托加入其中:

import 'package:flutter/material.dart';
import 'to_intl.dart'; // 导入自定义本地化文件

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      locale: const Locale('to'),
      localizationsDelegates: const [
        ToMaterialLocalizations.delegate, // 你已配置的Material委托
        ToCupertinoLocalizations.delegate, // 新增的Cupertino委托
        // 保留系统默认委托(如需支持其他语言)
        GlobalMaterialLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
      ],
      supportedLocales: const [
        Locale('to'),
        // 其他需支持的语言Locale
      ],
      home: const MyHomePage(),
    );
  }
}

3. 验证结果

重新运行应用,CupertinoLocalizations系统将找到to语言的对应委托,警告会自动消失。

注意事项

  • 必须完整实现CupertinoLocalizations抽象类的所有必填方法,否则会出现编译错误。
  • 如果你的应用完全不使用Cupertino风格组件,也可移除GlobalCupertinoLocalizations.delegate,但建议保留自定义委托以避免潜在问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 21:47:00