在flutter中动态地改变应用启动器图标

在本文中,我们将讨论如何在 Flutter 应用程序的运行时动态更改多个应用程序启动器图标。

在 pubspec.yaml 文件中添加以下依赖项。

flutter_dynamic_icon:https://pub.dev/packages/flutter_dynamic_icon

考虑我们已经准备好基本的 UI(包含图像和按钮小部件)。

import 'package:flutter/material.dart';
class MyHomePage extends StatefulWidget {
 const MyHomePage({Key? key, required this.title}) : super(key: key);
 final String title;
 @override
 State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
 int iconIndex = 0;
 List iconName = <String>['icon1', 'icon2', 'icon3'];
 @override
 Widget build(BuildContext context) {
 return Scaffold(
 appBar: buildAppBar(appBarTitle: widget.title),
 body: Padding(
 padding: EdgeInsets.all(kSpacing),
 child: Column(
 mainAxisAlignment: MainAxisAlignment.center,
 children: [
 buildIconTile(0, 'red'),
 buildIconTile(1, 'dark'),
 buildIconTile(2, 'blue'),
 HeightSpacer(myHeight: kSpacing),
 PrimaryBtn(
 btnFun: () => changeAppIcon(), btnText: 'Set as app icon'),
 ],
 )),
 );
 }
 Widget buildIconTile(int index, String themeTxt) => Padding(
 padding: EdgeInsets.all(kSpacing / 2),
 child: GestureDetector(
 onTap: () => setState(() => iconIndex = index),
 child: ListTile(
 contentPadding: const EdgeInsets.only(left: 0.0, right: 0.0),
 leading: Image.asset(
 imagefiles[index],
 width: 45,
 height: 45,
 ),
 title: Text(themeTxt, style: const TextStyle(fontSize: 25)),
 trailing: iconIndex == index
 ? const Icon(
 Icons.check_circle_rounded,
 color: Colors.green,
 size: 30,
 )
 : Icon(
 Icons.circle_outlined,
 color: Colors.grey.withOpacity(0.5),
 size: 30,
 )),
 ),
 );
 changeAppIcon() {}

现在我们需要在按钮小部件的 onpress 事件 [changeAppIcon{}] 中编写更改应用启动器图标的逻辑。

changeAppIcon() async {
 try {
 if (await FlutterDynamicIcon.supportsAlternateIcons) {
 await FlutterDynamicIcon.setAlternateIconName(iconName[iconIndex]);
 debugPrint("App icon change successful");
 return;
 }
 } catch (e) {
 debugPrint("Exception: ${e.toString()}");
 }
 debugPrint("Failed to change app icon ");
}

至此,我们完成了配置动态应用图标的编码部分。

现在要使该功能正常工作,我们需要在项目的 ios 文件夹中的 info.plist 文件中添加一些更改。

因此,我们需要通过右键单击 ios 文件夹在 xCode 中打开项目。

⚠️(注意:此功能针对 iOS 平台,因此我们需要 macOS 设备进行设置)。

在 xCode 中打开项目后,尝试在 Runner/Runner 文件夹中添加应用程序图标图像,如下所示。

接下来我们需要设置 info.plist 文件(按照下面给出的步骤)。

?将 Icon files (iOS 5) 添加到信息属性列表。

?将 CFBundleAlternateIcons作为一个字典添加到上面创建的 icon files(ios 5) 中。

?在 CFBundleAlternateIcons下创建3个字典,其名称与图标图像文件名相似(在我们的例子中是 icon1icon2icon3)。

?对于每个字典(icon1icon2icon3),需要创建两个属性——UIPrerenderedIconCFBundleIconFiles

?最后将 CFBundleIconFiles 改成一个 array ,并将 item0 的值添加到各自的字典中,作为 icon1icon2icon3

现在运行命令行

flutter clean
flutter pub get

就是这样。 ? 运行代码以查看它的实际效果。?

请参阅我的视频教程以获取完整指南:https://www.youtube.com/watch?v=412lSuyUJ_4
在此处获取完整的源代码:https://github.com/vijayinyoutube/dynamic_app_icon_app


原文:https://medium.com/vijay-r/dynamically-change-app-launcher-icon-in-flutter-b6302c591ac1

作者:Vijay R

作者:杭州程序员张张

%s 个评论

要回复文章请先登录注册