当前位置: 首页 > Web前端 > HTML

Flutter系列:如丝般顺滑的SliverAppBar

时间:2023-03-28 12:19:34 HTML

简介对于一个APP来说,一定要有一个AppBar,它一般包含了APP的导航信息。虽然我们可以使用一个固定的组件作为AppBar,但是这样会失去很多特效,比如将AppBar固定在顶部,AppBar在滑动过程中可以调整大小。当然,这一切都不需要自己去实现。Flutter为我们提供了一个非常强大的AppBar组件,叫做SliverAppBar。SliverAppBar详解首先看一下SliverAppBar的定义:classSliverAppBarextendsStatefulWidget可以看到SliverAppBar是一个StatefulWidget,它的state包含了一些配置信息,包括FloatingHeaderSnapConfiguration、OverScrollHeaderStretchConfiguration和PersistentHeaderShowOnScreenConfiguration。SliverAppBar可以接收很多属性,接下来我们将解释一些最重要和常用的属性。forceElevatedforceElevated是一个bool值,表示是否显示AppBar的阴影效果,默认值为false。primaryprimary用于配置AppBar的属性,表示AppBar是否显示在界面的Top位置。如果设置为true,AppBar将被放置在Top位置,使用的高度为系统状态栏的高度。floating是一个很重要的属性,因为对于SliverAppBar来说,当界面滚动离开SliverAppBar时,SliverAppBar会隐藏或者简称为状态栏的高度。浮动是指当我们滑动到SliverAppBar时,SliverAppBar是否浮动显示。pinned表示滚动时SliverAppBar是否固定在界面边缘。snapsnap是与floating一起使用的属性,snap表示滚动到SliverAppBar时是否立即完整显示SliverAppBar。automaticallyImplyLeadingautomaticallyImplyLeading是AppBar中使用的一个属性,表示是否需要实现leadingwidget。最常用的属性是浮动、固定和捕捉。还有一个flexibleSpace组件,是SliverAppBar悬浮时显示的widget,通常和expandedHeight配合使用。SliverAppBar的使用上面解释了SliverAppBar的构造函数和基本属性。接下来,我们将通过具体的例子来说明如何使用SliverAppBar。一般来说,SliverAppBar是和CustomScrollView一起使用的,也就是说SliverAppBar会封装在CustomScrollView中。除了SliverAppBar,其他sliver组件也可以添加到CustomScrollView中。首先我们定义一个SliverAppBar:SliverAppBar(pinned:true,snap:true,floating:true,expandedHeight:200.0,flexibleSpace:FlexibleSpaceBar(title:constText('SliverAppBar'),background:Image.asset("images/head.jpg"),),),这里我们设置pinned,snap,floating为true,然后设置expandedHeight和flexibleSpace。这里的flexibleSpaces是一个FlexibleSpaceBar对象,这里我们设置title和background属性。那么我们需要将SliverAppBar放到CustomScrollView中进行显示。Widgetbuild(BuildContextcontext){returnCustomScrollView(slivers:[SliverAppBar(...),SliverList(delegate:SliverChildBuilderDelegate((BuildContextcontext,intindex){返回Container(color:index.isOdd?Colors.white:Colors.green,height:100.0,child:Center(child:ListTile(title:Text('1888888888'+index.toString(),style:TextStyle(fontWeight:FontWeight.w500),),leading:Icon(Icons.contact_phone,颜色:Colors.blue[500],),),),);},childCount:10,),),],);除了SliverAppBar,我们还提供了一个SliverList,它使用了SliverChildBuilderDelega我们构造了10个ListTile对象,最后运行得到如下界面:默认情况下,SliverAppBar处于展开状态。如果我们滑动下面的SliverList,flexibleSpace会被隐藏,可以得到如下界面:当我们慢慢往上滑动的时候,因为设置了floating=true和snap=true,只要往上滑动,所有的flexibleSpace都会显示:当我们设置floating为false时,flexibleSpace只会向上滑动到顶部显示。总结简单来说,SliverAppBar就是一个滑动时改变大小的AppBar。我们可以通过设置不同的参数来实现不同的效果。本文示例:https://github.com/ddean2009/learn-flutter.git