惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Security Latest
Security Latest
Recorded Future
Recorded Future
人人都是产品经理
人人都是产品经理
S
SegmentFault 最新的问题
Hacker News - Newest:
Hacker News - Newest: "LLM"
C
CXSECURITY Database RSS Feed - CXSecurity.com
博客园 - 三生石上(FineUI控件)
博客园 - 聂微东
P
Privacy & Cybersecurity Law Blog
WordPress大学
WordPress大学
Know Your Adversary
Know Your Adversary
Spread Privacy
Spread Privacy
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
量子位
L
LINUX DO - 热门话题
L
Lohrmann on Cybersecurity
博客园 - Franky
酷 壳 – CoolShell
酷 壳 – CoolShell
T
Tor Project blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
雷峰网
雷峰网
阮一峰的网络日志
阮一峰的网络日志
V
Visual Studio Blog
T
Threatpost
T
Tenable Blog
有赞技术团队
有赞技术团队
大猫的无限游戏
大猫的无限游戏
Engineering at Meta
Engineering at Meta
GbyAI
GbyAI
C
Cisco Blogs
H
Heimdal Security Blog
Attack and Defense Labs
Attack and Defense Labs
A
About on SuperTechFans
Last Week in AI
Last Week in AI
N
News and Events Feed by Topic
T
Threat Research - Cisco Blogs
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
I
Intezer
V
V2EX
Cyberwarzone
Cyberwarzone
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
B
Blog RSS Feed
V
Vulnerabilities – Threatpost
N
Netflix TechBlog - Medium
T
The Blog of Author Tim Ferriss
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
U
Unit 42
PCI Perspectives
PCI Perspectives
P
Privacy International News Feed
D
Docker

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Dynamic App Icons in Flutter: The Ultimate Guide to Manual Selection & Over-the-Air Cloud Updates
Codexlancers · 2026-06-15 · via DEV Community

An application's home screen presence is prime real estate. Giving users the option to customize their app icon manually creates a delightful sense of personalization. Simultaneously, having the power to change app icons remotely allows you to ship global thematic shifts - like a festive holiday theme, a dark mode rebranding, or temporary promotional campaign artwork - without pushing a new build to the App Store or Google Play Store.

In this deep-dive guide, we will implement a dual-mode dynamic icon framework in Flutter without relying on buggy or outdated third-party packages. We will build our own MethodChannels using Kotlin and Swift to support two core features:

  1. Manual Selection: Letting the user pick their preference inside an settings UI menu.
  2. Over-the-Air Updates: Overriding or syncing the icon automatically using Firebase Remote Config.

Architectural Deep Dive

Before writing code, it is important to understand how the underlying platform behaviors differ. Flutter operates on a single execution context, meaning we must use platform channels to trigger native operating system APIs.

Android: Component Aliases

Android handles launcher icons statically via the AndroidManifest.xml. To circumvent this limitation, we declare multiple <activity-alias> tags that all point to the primary MainActivity. By toggling the enablement state of these aliases via the native PackageManager, the device home screen refreshes to reflect the icon linked to the active alias.

⚠️ Android Side Effect: Enabling or disabling an activity alias clears the recent apps stack and briefly kills the background application state to remap the launcher profile.

iOS: Alternate Icons API

Apple provides an explicit native framework via UIApplication.shared.setAlternateIconName(). Unlike standard graphic bundles, alternative icon resources cannot be included in a compiled asset catalog (Assets.xcassets). Instead, they must be bundled into the root app directory as loose files and mapped manually inside the project's properties dictionary (Info.plist).

Step 1: Building the Native Infrastructure

1. Flutter MethodChannel Connection

Create a clean utility class in your Dart project to establish the native system communication pipeline.

import 'package:flutter/services.dart';

class DynamicIconService {
  static const MethodChannel _channel = MethodChannel('com.dynamicicon.app/dynamic_icon');
  /// Requests the native OS platform layer to swap the active launcher asset icon profile.
  static Future<void> changeIcon(String iconName) async {
    try {
      await _channel.invokeMethod('setIcon', {'iconName': iconName});
    } on PlatformException catch (e) {
      print("Failed to change application launcher profile: '${e.message}'.");
    }
  }
}

2. Android Integration (AndroidManifest.xml & Kotlin)

First, add your alternative graphic assets directly to your resource directories:

  • android/app/src/main/res/mipmap-hdpi/ic_launcher_dark.png
  • android/app/src/main/res/mipmap-hdpi/ic_launcher_festive.png

Next, modify android/app/src/main/AndroidManifest.xml. Set the root .MainActivity property android:enabled to false. We will delegate all initial system hooks to our aliases.

<manifest xmlns:android="http://schemas.android.com/apk/res/android">
    <application
        android:label="Dynamic App"
        android:name="${applicationName}">

        <!-- Base Target Activity Framework (Deactivated) -->
        <activity
            android:name=".MainActivity"
            android:exported="true"
            android:enabled="false"
            android:launchMode="singleTop"
            android:theme="@style/LaunchTheme">
            <meta-data
                android:name="io.flutter.embedding.android.NormalTheme"
                android:resource="@style/NormalTheme" />
        </activity>

        <!-- Default Application Icon Alias -->
        <activity-alias
            android:name=".DefaultIcon"
            android:enabled="true"
            android:exported="true"
            android:icon="@mipmap/ic_launcher"
            android:targetActivity=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity-alias>

        <!-- Dark Variant Icon Alias -->
        <activity-alias
            android:name=".DarkIcon"
            android:enabled="false"
            android:exported="true"
            android:icon="@mipmap/ic_launcher_dark"
            android:targetActivity=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity-alias>

        <!-- Festive Variant Icon Alias -->
        <activity-alias
            android:name=".FestiveIcon"
            android:enabled="false"
            android:exported="true"
            android:icon="@mipmap/ic_launcher_festive"
            android:targetActivity=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity-alias>
    </application>
</manifest>

Open your MainActivity.kt file to receive channel methods and trigger the state switch loop:

package com.dynamicicon.app

import android.content.ComponentName
import android.content.pm.PackageManager
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel

class MainActivity: FlutterActivity() {
    private val CHANNEL = "com.dynamicicon.app/dynamic_icon"
    private val packageNamespace = "com.dynamicicon.app"
    private val aliasRegistry = listOf("DefaultIcon", "DarkIcon", "FestiveIcon")
    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)

        MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler { call, result ->
            if (call.method == "setIcon") {
                val targetIcon = call.argument<String>("iconName")
                if (targetIcon != null && aliasRegistry.contains(targetIcon)) {
                    toggleLauncherComponent(targetIcon)
                    result.success(null)
                } else {
                    result.error("ALIAS_NOT_FOUND", "The target alias mapping configuration is missing.", null)
                }
            } else {
                result.notImplemented()
            }
        }
    }
    private fun toggleLauncherComponent(targetAlias: String) {
        val pm = applicationContext.packageManager

        for (alias in aliasRegistry) {
            val componentState = if (alias == targetAlias) {
                PackageManager.COMPONENT_ENABLED_STATE_ENABLED
            } else {
                PackageManager.COMPONENT_ENABLED_STATE_DISABLED
            }

            pm.setComponentEnabledSetting(
                ComponentName(applicationContext, "$packageNamespace.$alias"),
                componentState,
                PackageManager.DONT_KILL_APP
            )
        }
    }
}

3. iOS Integration (Info.plist & Swift)

Drop your loose alternative icon images directly under the ios/Runner/ folder structure as un-cataloged raw items (e.g., ic_launcher_dark@2x.png, ic_launcher_festive@3x.png).

Register these keys in ios/Runner/Info.plist:

<key>CFBundleIcons</key>
<dict>
    <key>CFBundlePrimaryIcon</key>
    <dict>
        <key>CFBundleIconFiles</key>
        <array>
            <string>AppIcon</string>
        </array>
    </dict>
    <key>CFBundleAlternateIcons</key>
    <dict>
        <key>DarkIcon</key>
        <dict>
            <key>CFBundleIconFiles</key>
            <array>
                <string>ic_launcher_dark</string>
            </array>
            <key>UIPrerenderedIcon</key>
            <false/>
        </dict>
        <key>FestiveIcon</key>
        <dict>
            <key>CFBundleIconFiles</key>
            <array>
                <string>ic_launcher_festive</string>
            </array>
            <key>UIPrerenderedIcon</key>
            <false/>
        </dict>
    </dict>
</dict>

Open ios/Runner/AppDelegate.swift and configure the channel logic:

import UIKit
import Flutter

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {

    let controller : FlutterViewController = window?.rootViewController as! FlutterViewController
    let iconChannel = FlutterMethodChannel(name: "com.dynamicicon.app/dynamic_icon",
                                           binaryMessenger: controller.binaryMessenger)

    iconChannel.setMethodCallHandler({
      (call: FlutterMethodCall, result: @escaping FlutterResult) -> Void in
      guard call.method == "setIcon" else {
          result(FlutterMethodNotImplemented)
          return
      }

      if let arguments = call.arguments as? [String: Any],
         let iconName = arguments["iconName"] as? String {
          self.updateAlternateIcon(named: iconName, response: result)
      } else {
          result(FlutterError(code: "BAD_ARGS", message: "Arguments malformed", details: nil))
      }
    })
    GeneratedPluginRegistrant.register(with: self)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
  private func updateAlternateIcon(named targetName: String, response: @escaping FlutterResult) {
      if #available(iOS 10.3, *) {
          let systemKey = (targetName == "DefaultIcon") ? nil : targetName

          UIApplication.shared.setAlternateIconName(systemKey) { error in
              if let error = error {
                  response(FlutterError(code: "IOS_ERROR", message: error.localizedDescription, details: nil))
              } else {
                  response(null)
              }
          }
      } else {
          response(FlutterError(code: "UNSUPPORTED_OS", message: "Minimum OS layout required", details: nil))
      }
  }
}

Step 2: Implementing the Management Strategy

Now that our native code is ready, we need to balance manual selection with remote config updates.

To handle this cleanly, we'll establish a business rule priority: Firebase Remote Config acts as a global override. If a remote key is published from the cloud dashboard, it overrides manual user settings. If no cloud configuration override is set (or it returns 'DefaultIcon'), the application respects the user's manual in-app selection.

First, add your framework dependencies to your pubspec.yaml:

dependencies:
  flutter:
    sdk: flutter
  firebase_core: ^3.0.0
  firebase_remote_config: ^5.0.0
  shared_preferences: ^2.2.0

The Dual-Control Integration Engine

Create a manager file app_icon_manager.dart to cleanly orchestrate both sources:

import 'package:firebase_remote_config/firebase_remote_config.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dynamic_icon_service.dart';

class AppIconManager {
  static const String _remoteOverrideKey = 'cloud_icon_override';
  static const String _userPrefKey = 'user_selected_icon';
  static const String _activeCachedKey = 'currently_applied_icon';

  /// Mode 1: Executed manually when a user taps an in-app icon preference menu item
  static Future<void> updateUserIconPreference(String targetIconName) async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setString(_userPrefKey, targetIconName);

    // Evaluate if the cloud override is currently blocking changes before updating
    final FirebaseRemoteConfig remoteConfig = FirebaseRemoteConfig.instance;
    final String cloudOverride = remoteConfig.getString(_remoteOverrideKey);
    if (cloudOverride == 'DefaultIcon' || cloudOverride.isEmpty) {
      await _applyIconSafetyGuard(targetIconName);
    } else {
      print("User setting cached, but blocked by active Cloud Override: $cloudOverride");
    }
  }

  /// Mode 2: Triggered automatically during application launch to fetch cloud rules over-the-air
  static Future<void> syncCloudConfiguration() async {
    final FirebaseRemoteConfig remoteConfig = FirebaseRemoteConfig.instance;
    try {
      await remoteConfig.setDefaults(<String, dynamic>{_remoteOverrideKey: 'DefaultIcon'});
      await remoteConfig.setConfigSettings(RemoteConfigSettings(
        fetchTimeout: const Duration(seconds: 10),
        minimumFetchInterval: const Duration(hours: 2),
      ));
      bool updated = await remoteConfig.fetchAndActivate();
      if (!updated) return;
      final String cloudOverrideValue = remoteConfig.getString(_remoteOverrideKey);
      final SharedPreferences prefs = await SharedPreferences.getInstance();
      if (cloudOverrideValue != 'DefaultIcon' && cloudOverrideValue.isNotEmpty) {
        // Cloud override takes precedence
        await _applyIconSafetyGuard(cloudOverrideValue);
      } else {
        // Fall back to local user selection or fallback default
        final String userPreference = prefs.getString(_userPrefKey) ?? 'DefaultIcon';
        await _applyIconSafetyGuard(userPreference);
      }
    } catch (e) {
      print('Failed to synchronize Firebase Remote Config layer: $e');
    }
  }

  /// Evaluates and runs the method channel call only if a real delta is detected
  static Future<void> _applyIconSafetyGuard(String targetValue) async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    final String currentlyActive = prefs.getString(_activeCachedKey) ?? 'DefaultIcon';
    // Guard Clause: Stop redundant channel triggers to avoid execution loops or app flash cycles
    if (currentlyActive == targetValue) return;
    print('Modifying launcher layout state from $currentlyActive to $targetValue');
    await DynamicIconService.changeIcon(targetValue);
    await prefs.setString(_activeCachedKey, targetValue);
  }
}

Step 3: Wiring It to the UI Layer & Lifecycle Boot

To wrap things up, initialize our syncing layer inside your app's main() startup routine, and build a quick selection UI.

import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'app_icon_manager.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  // Run the cloud check instantly at boot time
  await AppIconManager.syncCloudConfiguration();
  runApp(const MyApp());
}
class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: SettingsIconScreen(),
    );
  }
}
class SettingsIconScreen extends StatelessWidget {
  const SettingsIconScreen({super.key});
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Customize App Icon')),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              'Select Your Preference:',
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 12),
            ListTile(
              leading: const Icon(Icons.phone_android),
              title: const Text('Default Classic Blue'),
              onTap: () => AppIconManager.updateUserIconPreference('DefaultIcon'),
            ),
            ListTile(
              leading: const Icon(Icons.dark_mode),
              title: const Text('Premium Minimalist Dark'),
              onTap: () => AppIconManager.updateUserIconPreference('DarkIcon'),
            ),
            ListTile(
              leading: const Icon(Icons.celebration),
              title: const Text('Festive Celebration Theme'),
              onTap: () => AppIconManager.updateUserIconPreference('FestiveIcon'),
            ),
          ],
        ),
      ),
    );
  }
}

Wrap Up & Cloud Control

Your application is now fully dual-controlled! To push a global theme override over the air:

  1. Open the Firebase Console and head to Remote Config.
  2. Create a parameter matching cloud_icon_override.
  3. Set its value to FestiveIcon (or keep it as DefaultIcon to defer to your user's preferences).
  4. Hit Publish Changes.