我收到以下带有代码A的警告信息,为什么?

Optional Modifier parameter should have a default value of Modifier

Code A

@Composable
fun DisplayIcon(
    modifier: Modifier=Modifier.size(24.dp),
    icon: ImageVector,
    tint: Color = Color.Blue
) {
    Icon(icon, null, modifier = modifier, tint = tint)
}

推荐答案

这只是一种最佳做法.使用其他一些缺省值可能会导致奇怪的情况-假设您想要在一列中使用此组件中的两个:

Column {
    DisplayIcon()
    DisplayIcon()
}

一切都很好,但现在您想要对齐其中之一:

Column {
    DisplayIcon()
    DisplayIcon(modifier = Modifier.align(Alignment.End))
}

And suddenly, with no apparent reason, one has different size than the other. So you have to find out from DisplayIcon implementation what's going on, and then probably add .size(24.dp) to your aligned composable as well. But now you want to change the default size, and you have to do so on many different places...
Something like this might be better solution:

@Composable
fun DisplayIcon(
    modifier: Modifier = Modifier,
    icon: ImageVector,
    tint: Color = Color.Blue,
    size: Dp = 24.dp,
) {
    Icon(icon, null, modifier = modifier.size(size), tint = tint)
}

Android相关问答推荐

错误:无法解析Symbol@style/Theme. Androidstudio in AndroidManifest.html for Kotlin Android Development''

list 合并失败,AGP 8.3.0

懒惰的垂直网格中盒子的重量-Jetpack组合

在Android上使用XSLT文件转换XML文件

Jetpack Compose:根据盒子中的最大视图固定宽度和高度

在 kotlin 上向适配器添加绑定视图功能

Jetpack Compose 使用 SavedStateHandle 发送返回结果不适用于 ViewModel 中注入的 SavedStateHandle

如何在 Android 的 ViewModel 中使用 LiveData

在段的中心绘制饼图(甜甜圈图)的图例

将 CircularProgressIndicator 添加到按钮而不增加其高度

AirDroid Business 如何能够从屏幕截图中排除覆盖?

无法通过 retrofit 解析对 kotlin 数据类的 xml 响应

try 使用 ViewPager2 实现滑动视图时出现类型不匹配错误

为什么按钮没有拉伸到屏幕边缘?

这是 let 函数的正确用法吗?

复用 RecyclerView 适配器,避免不必要的 API 调用

如何在android studio 2021.1中使用谷歌库以外的库

如何满足设备内框架的无效 Wear OS 屏幕截图Wear OS 表盘策略违规?

单个用户可以在 Firebase 身份验证中将多个电话号码链接到他的帐户吗?

lambda 函数中的类型不匹配 - Kotlin