考虑下面的示例,旨在在
问题是:如何基于实际的
CustomScrollView
内呈现具有潜在自定义长/短文本的固定标题栏。class TitleBar extends StatelessWidget {
TitleBar(this.text);
final String text;
@override
Widget build(BuildContext context) => Text(
text,
style: TextStyle(fontSize: 30),
maxLines: 3,
overflow: TextOverflow.ellipsis,
);
}
class TitleBarDelegate extends SliverPersistentHeaderDelegate {
final String text;
TitleBarDelegate(this.text);
@override
Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) => TitleBar(text);
@override
bool shouldRebuild(TitleBarDelegate oldDelegate) => oldDelegate.text != text;
@override
double get maxExtent => ???;
@override
double get minExtent => maxExtent; // doesn't shrink
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
body: CustomScrollView(
slivers: [
SliverPersistentHeader(
pinned: true,
delegate: TitleBarDelegate('Potentially very long text'),
),
SliverToBoxAdapter(
child: Text("Foo " * 1000),
),
],
),
),
);
}
}
问题是:如何基于实际的
TitleBar
计算maxExtent
。问题在于实际TitleBar
的大小取决于文本,因此通常无法提前计算。
请注意,TitleBar
可能具有比上面示例中更复杂的布局。因此,一般问题是如何“收缩包裹”SliverPersistentHeaderDelegate
。