问题描述
我想获取 CustomScrollView 小部件的整个高度。所以我做了一个下面的代码,但它不起作用。
@override
void initState(){
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) => getSizeAndPosition());
}
getSizeAndPosition() {
RenderBox _customScrollBox =
_customScrollKey.currentContext.findRenderObject();
_customScrollSize = _customScrollBox.size;
_customScrollPosition = _customScrollBox.localToGlobal(Offset.zero);
print(_customScrollSize.height);
setState(() {});
}
@override
Widget build(BuildContext context) {
return Scaffold(
key: _customScrollKey,appBar: _appbar(),body: CustomScrollView(
controller: _controller,slivers: [
SliverList(
delegate: SliverChildListDelegate([
_titleSection(),_thumnail(),SizedBox(
height: 40,),])),],);
}
这段代码得到的高度没有考虑customScrollview中list的高度。我的意思是,_customScrollSize.height
和 MediaQuery.of(context).size.width
是一样的。
_controller.addListener(() {
setState(() {
if (_controller.offset < 0) {
scrollHeight = 0;
} else {
scrollHeight = _controller.offset;
}
});
});
Container(
width: size.width * (scrollHeight / _customScrollSize.height),decoration: Boxdecoration(
border: Border(
bottom: BorderSide(
width: 1)),
上面的代码中,'_customScrollSize.height'没有反映整体高度,因此该功能没有正确实现。这种情况有什么好的使用方法吗?
解决方法
使用 sliver 创建自定义滚动效果的 ScrollView。
CustomScrollView 允许您直接提供条带以创建各种滚动效果,例如列表、网格和扩展标题。例如,要创建一个滚动视图,其中包含一个扩展应用栏,后跟一个列表和一个网格,请使用包含三个条块的列表:SliverAppBar
、SliverList
和 SliverGrid
。>
在您的情况下,请删除 appBar 并在自定义滚动视图中使用 sliverAppBar,您可以为其他孩子使用 sliverfillRemaining 小部件
示例
CustomScrollView(
slivers: <Widget>[
const SliverAppBar(
pinned: true,expandedHeight: 250.0,flexibleSpace: FlexibleSpaceBar(
title: Text('Demo'),),SliverList(
delegate: SliverChildListDelegate([
_titleSection(),_thumnail(),SizedBox(
height: 40,])),...