我有同样的情况。我发现:
Top app bar specs文档中提到TopAppBar的容器具有"Surface"角色和Elevation (on scroll) Level 2。
在Color system - Color roles页面上,我发现以下信息:
在高度为+2时,带有表面颜色容器的组件会收到一个具有8%不透明度的主要颜色覆盖层。
因此,默认的TopAppBarLayout样式将使用?attr/colorSurface作为背景颜色,并使用8%不透明度的?attr/colorPrimary作为叠加层(一种蒙版效果)。
我的解决方法:
为AppBarLayout创建一个样式,并将android:outlineAmbientShadowColor和android:outlineSpotShadowColor设置为黑色(因为它是创建阴影的默认颜色)。在Widget.Material3.AppBarLayout中,这些属性被设置为透明。
<style name="Widget.App.AppBarLayout" parent="Widget.Material3.AppBarLayout">
<item name="android:outlineAmbientShadowColor" ns1:ignore="NewApi">@android:color/black</item>
<item name="android:outlineSpotShadowColor" ns1:ignore="NewApi">@android:color/black</item>
</style>
除上述方法外,您还可以添加一个android:background属性并设置颜色,或者添加一个materialThemeOverlay属性将colorSurface设置为您的颜色(背景),并将colorPrimary设置为@ android: transparent(叠加层)。 我更喜欢直接添加 android:background,因为添加 materialThemeOverlay 可能会影响您的 AppBarLayout 的子视图。
<style name="Widget.App.AppBarLayout" parent="Widget.Material3.AppBarLayout">
<item name="android:outlineAmbientShadowColor" ns1:ignore="NewApi">@android:color/black</item>
<item name="android:outlineSpotShadowColor" ns1:ignore="NewApi">@android:color/black</item>
<item name="android:background">@color/white</item>
</style>
<style name="Widget.App.AppBarLayout" parent="Widget.Material3.AppBarLayout">
<item name="android:outlineAmbientShadowColor" ns1:ignore="NewApi">@android:color/black</item>
<item name="android:outlineSpotShadowColor" ns1:ignore="NewApi">@android:color/black</item>
<item name="materialThemeOverlay">@style/ThemeOverlay.App.DayNight.NoActionBar</item>
</style>
<style name="ThemeOverlay.App.DayNight.NoActionBar" parent="Theme.Material3.DayNight.NoActionBar">
<item name="colorPrimary">@android:color/transparent</item>
<item name="colorSurface">@android:color/white</item>
</style>
不要忘记将你的样式应用到AppBarLayout或主题中。
顺便说一下,在< strong>Widget.Material3.AppBarLayout 中设置了liftOnScroll属性为true,所以没有必要设置它。仅为滚动视图设置 layout_behavior 即可使所有内容正常工作。
return Scaffold(
key: _scaffoldMessengerKey,
appBar: AppBar(
elevation: 6,
shadowColor: Colors.black.withOpacity(.5),
...
)
...
)
return MaterialApp(
title: 'Flutter App',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(
seedColor: Colors.red,
background: Colors.grey.shade50,
),
useMaterial3: true,
appBarTheme: AppBarTheme.of(context).copyWith(
elevation: 6,
shadowColor: Colors.black.withOpacity(.5),
),
),
...
);
你可以从Material文档中使用特殊属性来定制你的主题。
<style name="AppTheme" parent="Theme.Material3.Light.NoActionBar">
<item name="elevationOverlayEnabled">false</item>
</style>