如何将卡片小部件放在 SliverAppBar 中?
Posted
技术标签:
【中文标题】如何将卡片小部件放在 SliverAppBar 中?【英文标题】:How to put a Card widget inside a SliverAppBar? 【发布时间】:2021-11-22 00:37:54 【问题描述】:我是 Flutter 的初学者。我正在尝试制作像this 这样的小部件。不幸的是,我仍然在努力实施它们。我尝试使用灵活的空格键在容器中进行一些对齐。但它并没有如我所愿。有没有办法把那张卡放在 SliverAppBar 上?这是我的代码。
Header.dart
Widget build(BuildContext context)
return SliverAppBar(
expandedHeight: 25.h,
backgroundColor: celticBlue,
actions: [
IconButton(
icon: const Icon(Icons.more_vert),
onPressed: () ,
),
],
title: Text('Quran', style: whiteHeading16),
centerTitle: true,
shadowColor: danube,
pinned: true,
elevation: 1,
shape: const ContinuousRectangleBorder(
borderRadius: BorderRadius.only(
bottomLeft: Radius.elliptical(100, 50),
bottomRight: Radius.elliptical(50, 100),
),
),
flexibleSpace: Padding(
padding: const EdgeInsets.all(25),
child: Container(
color: Colors.redAccent,
alignment: Alignment.bottomCenter,
height: 15.h,
),
),
);
这里是the result
【问题讨论】:
使用 PreferredSize 应用栏 @AkbarMasterpadi thx,但是把那个放在哪里?在灵活空格键上?还是应该将其更改为 AppBar 而不是 Sliver ? 【参考方案1】:您可以使用 SliverPersistentHeaderDelegate 和 Stack 小部件来做到这一点,请查看我的示例
class PlayingSliversState extends State<PlayingSlivers>
@override
Widget build(BuildContext context)
return Scaffold(
body: SafeArea(
child: CustomScrollView(
slivers: <Widget>[
SliverPersistentHeader(
pinned: true,
floating: true,
delegate: CustomSliverDelegate(
expandedHeight: 120,
),
),
SliverFillRemaining(
child: Center(
child: Text("data"),
),
),
],
),
),
);
class CustomSliverDelegate extends SliverPersistentHeaderDelegate
final double expandedHeight;
final bool hideTitleWhenExpanded;
CustomSliverDelegate(
@required this.expandedHeight,
this.hideTitleWhenExpanded = true,
);
@override
Widget build(
BuildContext context, double shrinkOffset, bool overlapsContent)
final appBarSize = expandedHeight - shrinkOffset;
final cardTopPosition = expandedHeight / 2 - shrinkOffset;
final proportion = 2 - (expandedHeight / appBarSize);
final percent = proportion < 0 || proportion > 1 ? 0.0 : proportion;
return SizedBox(
height: expandedHeight + expandedHeight / 2,
child: Stack(
children: [
SizedBox(
height: appBarSize < kToolbarHeight ? kToolbarHeight : appBarSize,
child: AppBar(
backgroundColor: Colors.green,
leading: IconButton(
icon: Icon(Icons.menu),
onPressed: () ,
),
elevation: 0.0,
title: Opacity(
opacity: hideTitleWhenExpanded ? 1.0 - percent : 1.0,
child: Text("Test")),
),
),
Positioned(
left: 0.0,
right: 0.0,
top: cardTopPosition > 0 ? cardTopPosition : 0,
bottom: 0.0,
child: Opacity(
opacity: percent,
child: Padding(
padding: EdgeInsets.symmetric(horizontal: 30 * percent),
child: Card(
elevation: 20.0,
child: Center(
child: Text("Header"),
),
),
),
),
),
],
),
);
@override
double get maxExtent => expandedHeight + expandedHeight / 2;
@override
double get minExtent => kToolbarHeight;
@override
bool shouldRebuild(SliverPersistentHeaderDelegate oldDelegate)
return true;
结果 您可以根据自己的意愿编辑此代码,然后查看
【讨论】:
以上是关于如何将卡片小部件放在 SliverAppBar 中?的主要内容,如果未能解决你的问题,请参考以下文章