ホーム 暮らし Flutter iOS Build Error: How to Resolve IconData Tree Shaking Issues

Flutter iOS Build Error: How to Resolve IconData Tree Shaking Issues

藤崎 健人 藤崎 健人 • 更新: • 公開: • 読了約 11 分
目次


nfb2487cad44f

Error Encountered

When attempting to build a Flutter app for iOS, I encountered the following error.

This application cannot tree shake icons fonts. It has non-constant instances of IconData at the following locations:
  - file:///path/to/project/lib/models/category.dart:27:13
Target release_ios_bundle_flutter_assets failed: Error: Avoid non-constant invocations of IconData or try to build again with --no-tree-shake-icons.

This error occurs due to code that dynamically generates icons.

Why this error occurs

Flutter has an optimization feature called Tree Shaking designed to reduce app size. This feature automatically excludes unused code and resources (including icon fonts) to make the app lighter.

However, if you write code like the following, Flutter cannot determine which icons will be used at build time.

// ❌ 問題のあるコード
factory CustomCategory.fromJson(Map<String, dynamic> json) 
  return CustomCategory(
    icon: IconData(  // <- ここが問題!
      json['iconCodePoint'],  // 変数を使っている
      fontFamily: 'MaterialIcons',
    ),
  );

Because a variable is passed to the IconData constructor, it cannot statically determine which icons are needed during the build, resulting in an error.

Solution

Quick Fix: Disable Tree Shaking (Not Recommended)

If you need to get the app running immediately, add the --no-tree-shake-icons option to your build command.

flutter build ios --release --no-tree-shake-icons

However, this method bundles all icon fonts, which will increase the app size by several MB to 10MB. Use this only as an emergency measure and it is recommended to transition to the correct solution described below.

Recommended Solution: Use Icon Mapping

Stop generating IconData dynamically and use a predefined icon mapping instead.

// ✅ 修正後のコード
factory CustomCategory.fromJson(Map<String, dynamic> json) 
  final IconData icon = _getIconFromCodePoint(json['iconCodePoint']);

  return CustomCategory(
    icon: icon,  // 事前定義されたアイコンを使用
  );


// アイコンマッピング用のヘルパーメソッド
static IconData _getIconFromCodePoint(int codePoint) 
  // よく使うアイコンを事前に定義
  const iconMap = 
    0xe8b8: Icons.work_rounded,
    0xe7fd: Icons.person_rounded,
    0xe80c: Icons.school_rounded,
    0xe87d: Icons.favorite_rounded,
    0xe227: Icons.attach_money_rounded,
    0xe8cc: Icons.shopping_cart_rounded,
    0xe88a: Icons.home_rounded,
    // 必要に応じてアイコンを追加
  ;

  // 未定義の場合はデフォルトアイコンを返す
  return iconMap[codePoint] ?? Icons.more_horiz_rounded;

How to find icon codes

You can easily find the code point for the icon you want to use with the following code.

// 例:work_rounded アイコンのコードポイントを16進数で取得
print(Icons.work_rounded.codePoint.toRadixString(16)); // "e8b8" が出力される

By adding the retrieved code point to the iconMap mentioned earlier, you will be able to use the new icon.

More practical implementation patterns

When managing icons across the entire project, creating a dedicated utility class will improve maintainability.

class AppIcons 
  // カテゴリごとのアイコンを文字列キーで管理
  static const Map<String, IconData> categoryIcons = 
    'work': Icons.work_rounded,
    'personal': Icons.person_rounded,
    'study': Icons.school_rounded,
    'health': Icons.favorite_rounded,
    'finance': Icons.attach_money_rounded,
    'shopping': Icons.shopping_cart_rounded,
    'home': Icons.home_rounded,
    // プロジェクトで使用するアイコンをすべて列挙
  ;

  // キーからアイコンを取得するメソッド
  static IconData getIcon(String key) 
    return categoryIcons[key] ?? Icons.more_horiz_rounded;
  

  // コードポイントからアイコンを取得するメソッド
  static IconData getIconFromCodePoint(int codePoint) 
    // categoryIcons の値から該当するアイコンを検索
    for (final icon in categoryIcons.values) 
      if (icon.codePoint == codePoint) 
        return icon;
      
    
    return Icons.more_horiz_rounded;
  


// 使用例
final icon = AppIcons.getIcon('work');
final iconFromCode = AppIcons.getIconFromCodePoint(0xe8b8);

Summary

Flutter build errors caused by tree shaking are due to the dynamic generation of IconData. To resolve this issue, it is important to avoid the IconData(variable) pattern using variables and instead use a mapping of predefined icons.

With this approach, you can resolve build errors while keeping the app size optimized. Additionally, creating a utility class for icon management can improve code maintainability.

I hope this is helpful to someone.

同じカテゴリの記事

藤崎 健人

芸能取材歴10年のデスク。所属事務所の公式リリース、番組公式サイト、配信サービスの告知を一次情報として採用し、裏付けの取れない内容は記事にしていません。

おすすめの関連記事