Flutter应用图标切换插件launcher_icon_switcher的使用
Flutter应用图标切换插件launcher_icon_switcher的使用
Launcher Icon Switcher 是一个Flutter插件,允许您动态更改应用程序的启动图标。下面将详细介绍其使用方法,并提供一个完整的示例demo。
插件概述
![]()
动态切换图标效果演示
| iOS | Android | 
|---|---|
生成图标
首先需要为您的应用程序生成一些图标。可以使用 flutter_launcher_icons 包来完成此操作。对于iOS图标名称,请使用驼峰命名法(CamelCase),因为这些名称也将在Android上用于活动别名。
flutter_launcher_icons:
  android: "snake_case_icon"
  ios: "CamelCaseIcon"
  remove_alpha_ios: true
  image_path_ios: "assets/launcher/icon-ios.png"
  image_path_android: "assets/launcher/icon-android.png"
平台设置
为了让这个插件正常工作,需要进行一些特定于平台的设置。以下是针对Android和iOS的详细说明。
Android
添加活动别名
一旦生成了Android图标,可以通过添加活动别名来使用它们作为启动图标。在AndroidManifest.xml文件中禁用主活动,并为每个图标添加活动别名元素:
<activity
    android:name=".MainActivity"
    android:exported="true"
    android:launchMode="singleTop"
    android:theme="@style/LaunchTheme"
    android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
    android:hardwareAccelerated="true"
    android:windowSoftInputMode="adjustResize"
    android:enabled="false">
    <meta-data
        android:name="io.flutter.embedding.android.NormalTheme"
        android:resource="@style/NormalTheme" />
    <intent-filter>
        <action android:name="android.intent.action.MAIN"/>
        <category android:name="android.intent.category.LAUNCHER"/>
    </intent-filter>
</activity>
<activity-alias
    android:name=".DefaultIcon"
    android:icon="@mipmap/default_icon"
    android:enabled="true"
    android:exported="true"
    android:targetActivity=".MainActivity">
    <intent-filter>
        <action android:name="android.intent.action.MAIN"/>
        <category android:name="android.intent.category.LAUNCHER"/>
    </intent-filter>
</activity-alias>
<activity-alias
    android:name=".AdditionalIcon"
    android:icon="@mipmap/additional_icon"
    android:enabled="false"
    android:exported="true"
    android:targetActivity=".MainActivity">
    <intent-filter>
        <action android:name="android.intent.action.MAIN"/>
        <category android:name="android.intent.category.LAUNCHER"/>
    </intent-filter>
</activity-alias>
确保只有默认别名是启用状态。
iOS
启用iOS备用应用图标
打开iOS项目,在Xcode中选择您的应用目标,前往 Build Settings 标签页并做如下修改:
- 启用 
Include All App Icon Assets选项 - 将所有图标添加到 
Alternate App Icon Sets - 设置 
Primary App Icon Set Name为您默认的图标 
![]()
使用方法
初始化插件
首先需要初始化插件,并传递图标列表及默认图标名称:
LauncherIconSwitcher().initialize(['DefaultIcon', 'AdditionalIcon', 'OneMoreIcon'], 'DefaultIcon');
获取当前图标
要获取当前启用的图标,调用以下方法:
LauncherIconSwitcher().getCurrentIcon();
更新启动图标
要设置新的启动图标,调用以下方法:
LauncherIconSwitcher().setIcon('AdditionalIcon');
更多详细的使用示例,可以参考 这里。
示例代码
下面是一个完整的示例demo,展示了如何使用 launcher_icon_switcher 插件实现图标切换功能。
import 'package:flutter/material.dart';
import 'package:launcher_icon_switcher/launcher_icon_switcher.dart';
void main() {
  runApp(const MyApp());
}
class MyApp extends StatefulWidget {
  const MyApp({super.key});
  @override
  State<MyApp> createState() => _MyAppState();
}
enum AppIcons {
  whiteBlue('WhiteBlue'),
  whitePink('WhitePink'),
  blackBlue('BlackBlue'),
  blackPink('BlackPink');
  final String name;
  const AppIcons(this.name);
}
class _MyAppState extends State<MyApp> {
  final _launcherIconSwitcherPlugin = LauncherIconSwitcher();
  bool isInitialized = false;
  String? currentIcon;
  @override
  void initState() {
    initPlugin();
    super.initState();
  }
  Future initPlugin() async {
    await _launcherIconSwitcherPlugin.initialize(
        AppIcons.values.map((e) => e.name).toList(), AppIcons.whiteBlue.name);
    currentIcon = await _launcherIconSwitcherPlugin.getCurrentIcon();
    setState(() => isInitialized = true);
  }
  Future changeIcon(AppIcons icon) async {
    await _launcherIconSwitcherPlugin.setIcon(icon.name);
    setState(() => currentIcon = icon.name);
  }
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Center(
          child: isInitialized
              ? Wrap(
                  spacing: 50,
                  runSpacing: 50,
                  alignment: WrapAlignment.center,
                  children: AppIcons.values
                      .map((e) => GestureDetector(
                            onTap: () => changeIcon(e),
                            child: Container(
                              width: 100,
                              height: 100,
                              decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(15),
                                  border: Border.all(
                                      color: currentIcon == e.name
                                          ? Colors.green
                                          : Colors.black45,
                                      width: 2),
                                  image: DecorationImage(
                                      image: AssetImage(
                                          'assets/sharp-${e.name.replaceAllMapped(RegExp(r'[A-Z]'), (match) => ' ${match.group(0)!.toLowerCase()}').trim().split(' ').join('-')}.png'))),
                            ),
                          ))
                      .toList(),
                )
              : const CircularProgressIndicator(),
        ),
      ),
    );
  }
}
以上就是关于 launcher_icon_switcher 插件的全部内容,希望对您有所帮助!
更多关于Flutter应用图标切换插件launcher_icon_switcher的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter应用图标切换插件launcher_icon_switcher的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,下面是一个关于如何在Flutter项目中使用launcher_icon_switcher插件来切换应用图标的示例代码。
首先,确保你已经在你的pubspec.yaml文件中添加了launcher_icon_switcher依赖项:
dependencies:
  flutter:
    sdk: flutter
  launcher_icon_switcher: ^latest_version  # 请替换为最新的版本号
然后,运行flutter pub get来安装依赖项。
接下来,你需要准备一些图标资源。将这些图标资源放在你的assets目录下,比如assets/icons/icon1.png和assets/icons/icon2.png。
确保在pubspec.yaml文件中声明这些资源:
flutter:
  assets:
    - assets/icons/icon1.png
    - assets/icons/icon2.png
然后,你可以在你的Flutter应用中使用launcher_icon_switcher插件来切换应用图标。以下是一个完整的示例代码:
import 'package:flutter/material.dart';
import 'package:launcher_icon_switcher/launcher_icon_switcher.dart';
void main() {
  runApp(MyApp());
}
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}
class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('App Icon Switcher Demo'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            ElevatedButton(
              onPressed: () async {
                try {
                  await LauncherIconSwitcher.setLauncherIcon(
                    context,
                    LauncherIconSwitcher.IconResource(
                      name: 'icon1',
                      path: 'assets/icons/icon1.png',
                      adaptiveIcon: false, // 如果你的图标是自适应图标,设置为true
                      adaptiveIconForeground: null, // 自适应图标前景色资源
                      adaptiveIconBackground: null, // 自适应图标背景色资源
                    ),
                  );
                  ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(content: Text('Icon 1 set successfully')),
                  );
                } catch (e) {
                  ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(content: Text('Failed to set icon: $e')),
                  );
                }
              },
              child: Text('Set Icon 1'),
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: () async {
                try {
                  await LauncherIconSwitcher.setLauncherIcon(
                    context,
                    LauncherIconSwitcher.IconResource(
                      name: 'icon2',
                      path: 'assets/icons/icon2.png',
                      adaptiveIcon: false, // 如果你的图标是自适应图标,设置为true
                      adaptiveIconForeground: null, // 自适应图标前景色资源
                      adaptiveIconBackground: null, // 自适应图标背景色资源
                    ),
                  );
                  ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(content: Text('Icon 2 set successfully')),
                  );
                } catch (e) {
                  ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(content: Text('Failed to set icon: $e')),
                  );
                }
              },
              child: Text('Set Icon 2'),
            ),
          ],
        ),
      ),
    );
  }
}
在这个示例中,我们创建了两个按钮,分别用于将应用图标设置为icon1.png和icon2.png。当用户点击按钮时,LauncherIconSwitcher.setLauncherIcon方法会被调用,并尝试设置新的应用图标。如果操作成功,会显示一个SnackBar提示;如果失败,会显示错误信息。
请注意,并非所有设备和操作系统版本都支持动态更改应用图标。因此,在实际使用中,你可能需要处理一些兼容性问题,并提示用户仅在支持的设备和版本上进行操作。
        
      
            
            
            
