flutter ListView 页面滚动组件
ListView class
A scrollable list of widgets arranged linearly.
ListView is the most commonly used scrolling widget. It displays its children one after another in the scroll direction. In the cross axis, the children are required to fill the ListView.
If non-null, the itemExtent forces the children to have the given extent in the scroll direction. Specifying an itemExtent is more efficient than letting the children determine their own extent because the scrolling machinery can make use of the foreknowledge of the children's extent to save work, for example when the scroll position changes drastically.
There are four options for constructing a ListView:
The default constructor takes an explicit List<Widget> of children. This constructor is appropriate for list views with a small number of children because constructing the List requires doing work for every child that could possibly be displayed in the list view instead of just those children that are actually visible.
The ListView.builder constructor takes an IndexedWidgetBuilder, which builds the children on demand. This constructor is appropriate for list views with a large (or infinite) number of children because the builder is called only for those children that are actually visible.
The ListView.separated constructor takes two IndexedWidgetBuilders:
itemBuilder
builds child items on demand, andseparatorBuilder
similarly builds separator children which appear in between the child items. This constructor is appropriate for list views with a fixed number of children.The ListView.custom constructor takes a SliverChildDelegate, which provides the ability to customize additional aspects of the child model. For example, a SliverChildDelegate can control the algorithm used to estimate the size of children that are not actually visible.
To control the initial scroll offset of the scroll view, provide a controller with its ScrollController.initialScrollOffset property set.
By default, ListView will automatically pad the list's scrollable extremities to avoid partial obstructions indicated by MediaQuery's padding. To avoid this behavior, override with a zero padding property.
ListView.builder(
padding: EdgeInsets.all(8.0),
itemExtent: 20.0,
itemBuilder: (BuildContext context, int index) {
return Text('entry $index');
},
)
Child elements' lifecycle
Creation
While laying out the list, visible children's elements, states and render objects will be created lazily based on existing widgets (such as when using the default constructor) or lazily provided ones (such as when using the ListView.builder constructor).
Destruction
When a child is scrolled out of view, the associated element subtree, states and render objects are destroyed. A new child at the same position in the list will be lazily recreated along with new elements, states and render objects when it is scrolled back.
Destruction mitigation
In order to preserve state as child elements are scrolled in and out of view, the following options are possible:
Moving the ownership of non-trivial UI-state-driving business logic out of the list child subtree. For instance, if a list contains posts with their number of upvotes coming from a cached network response, store the list of posts and upvote number in a data model outside the list. Let the list child UI subtree be easily recreate-able from the source-of-truth model object. Use StatefulWidgets in the child widget subtree to store instantaneous UI state only.
Letting KeepAlive be the root widget of the list child widget subtree that needs to be preserved. The KeepAlive widget marks the child subtree's top render object child for keep-alive. When the associated top render object is scrolled out of view, the list keeps the child's render object (and by extension, its associated elements and states) in a cache list instead of destroying them. When scrolled back into view, the render object is repainted as-is (if it wasn't marked dirty in the interim).
This only works if
addAutomaticKeepAlives
andaddRepaintBoundaries
are false since those parameters cause the ListView to wrap each child widget subtree with other widgets.Using AutomaticKeepAlive widgets (inserted by default when
addAutomaticKeepAlives
is true). Instead of unconditionally caching the child element subtree when scrolling off-screen like KeepAlive,AutomaticKeepAlive can let whether to cache the subtree be determined by descendant logic in the subtree.As an example, the EditableText widget signals its list child element subtree to stay alive while its text field has input focus. If it doesn't have focus and no other descendants signaled for keep-alive via aKeepAliveNotification, the list child element subtree will be destroyed when scrolled away.
AutomaticKeepAlive descendants typically signal it to be kept alive by using the AutomaticKeepAliveClientMixin, then implementing the
wantKeepAlive
getter and callingupdateKeepAlive
.
Transitioning to CustomScrollView
A ListView is basically a CustomScrollView with a single SliverList in its CustomScrollView.slivers property.
If ListView is no longer sufficient, for example because the scroll view is to have both a list and a grid, or because the list is to be combined with a SliverAppBar, etc, it is straight-forward to port code from usingListView to using CustomScrollView directly.
The key, scrollDirection, reverse, controller, primary, physics, and shrinkWrap properties on ListView map directly to the identically named properties on CustomScrollView.
The CustomScrollView.slivers property should be a list containing either a SliverList or a SliverFixedExtentList; the former if itemExtent on the ListView was null, and the latter if itemExtent was not null.
The childrenDelegate property on ListView corresponds to the SliverList.delegate (or SliverFixedExtentList.delegate) property. The new ListView constructor's children
argument corresponds to the childrenDelegate being a SliverChildListDelegate with that same argument. The new ListView.builderconstructor's itemBuilder
and childCount
arguments correspond to the childrenDelegate being aSliverChildBuilderDelegate with the matching arguments.
The padding property corresponds to having a SliverPadding in the CustomScrollView.slivers property instead of the list itself, and having the SliverList instead be a child of the SliverPadding.
CustomScrollViews don't automatically avoid obstructions from MediaQuery like ListViews do. To reproduce the behavior, wrap the slivers in SliverSafeAreas.
Once code has been ported to use CustomScrollView, other slivers, such as SliverGrid or SliverAppBar, can be put in the CustomScrollView.slivers list.
ListView(
shrinkWrap: true,
padding: const EdgeInsets.all(20.0),
children: <Widget>[
const Text('I\'m dedicating every day to you'),
const Text('Domestic life was never quite my style'),
const Text('When you smile, you knock me out, I fall apart'),
const Text('And I thought I was so smart'),
],
)
CustomScrollView(
shrinkWrap: true,
slivers: <Widget>[
SliverPadding(
padding: const EdgeInsets.all(20.0),
sliver: SliverList(
delegate: SliverChildListDelegate(
<Widget>[
const Text('I\'m dedicating every day to you'),
const Text('Domestic life was never quite my style'),
const Text('When you smile, you knock me out, I fall apart'),
const Text('And I thought I was so smart'),
],
),
),
),
],
)
See also:
- SingleChildScrollView, which is a scrollable widget that has a single child.
- PageView, which is a scrolling list of child widgets that are each the size of the viewport.
- GridView, which is scrollable, 2D array of widgets.
- CustomScrollView, which is a scrollable widget that creates custom scroll effects using slivers.
- ListBody, which arranges its children in a similar manner, but without scrolling.
- ScrollNotification and NotificationListener, which can be used to watch the scroll position without using a ScrollController.
- Inheritance
Constructors
- ListView({Key key, Axis scrollDirection: Axis.vertical, bool reverse: false, ScrollController controller, bool primary, ScrollPhysics physics, bool shrinkWrap: false, EdgeInsetsGeometry padding, double itemExtent, bool addAutomaticKeepAlives: true, bool addRepaintBoundaries: true, bool addSemanticIndexes: true, double cacheExtent, List<Widget> children: const [], int semanticChildCount, DragStartBehavior dragStartBehavior: DragStartBehavior.down })
- Creates a scrollable, linear array of widgets from an explicit List. [...]
- ListView.builder({Key key, Axis scrollDirection: Axis.vertical, bool reverse: false, ScrollController controller, bool primary, ScrollPhysics physics, bool shrinkWrap: false, EdgeInsetsGeometry padding, double itemExtent, @required IndexedWidgetBuilder itemBuilder, int itemCount, bool addAutomaticKeepAlives: true, bool addRepaintBoundaries: true, bool addSemanticIndexes: true, double cacheExtent, int semanticChildCount, DragStartBehavior dragStartBehavior: DragStartBehavior.down })
- Creates a scrollable, linear array of widgets that are created on demand. [...]
- ListView.custom({Key key, Axis scrollDirection: Axis.vertical, bool reverse: false, ScrollController controller, bool primary, ScrollPhysics physics, bool shrinkWrap: false, EdgeInsetsGeometry padding, double itemExtent, @required SliverChildDelegate childrenDelegate, double cacheExtent, int semanticChildCount })
- Creates a scrollable, linear array of widgets with a custom child model. [...]
const
- ListView.separated({Key key, Axis scrollDirection: Axis.vertical, bool reverse: false, ScrollController controller, bool primary, ScrollPhysics physics, bool shrinkWrap: false, EdgeInsetsGeometry padding, @required IndexedWidgetBuilder itemBuilder, @required IndexedWidgetBuilder separatorBuilder, @required int itemCount, bool addAutomaticKeepAlives: true, bool addRepaintBoundaries: true, bool addSemanticIndexes: true, double cacheExtent })
- Creates a fixed-length scrollable linear array of list "items" separated by list item "separators". [...]
Properties
- childrenDelegate → SliverChildDelegate
- A delegate that provides the children for the ListView. [...]
final
- itemExtent → double
- If non-null, forces the children to have the given extent in the scroll direction. [...]
final
- anchor → double
- The relative position of the zero scroll offset. [...]
final, inherited
- cacheExtent → double
- The viewport has an area before and after the visible area to cache items that are about to become visible when the user scrolls. [...]
final, inherited
- center → Key
- The first child in the GrowthDirection.forward growth direction. [...]
final, inherited
- controller → ScrollController
- An object that can be used to control the position to which this scroll view is scrolled. [...]
final, inherited
- dragStartBehavior → DragStartBehavior
- Determines the way that drag start behavior is handled. [...]
final, inherited
- hashCode → int
- The hash code for this object. [...]
read-only, inherited
- key → Key
- Controls how one widget replaces another widget in the tree. [...]
final, inherited
- padding → EdgeInsetsGeometry
- The amount of space by which to inset the children.
final, inherited
- physics → ScrollPhysics
- How the scroll view should respond to user input. [...]
final, inherited
- primary → bool
- Whether this is the primary scroll view associated with the parent PrimaryScrollController. [...]
final, inherited
- reverse → bool
- Whether the scroll view scrolls in the reading direction. [...]
final, inherited
- runtimeType → Type
- A representation of the runtime type of the object.
read-only, inherited
- scrollDirection → Axis
- The axis along which the scroll view scrolls. [...]
final, inherited
- semanticChildCount → int
- The number of children that will contribute semantic information. [...]
final, inherited
- shrinkWrap → bool
- Whether the extent of the scroll view in the scrollDirection should be determined by the contents being viewed. [...]
final, inherited
Methods
- buildChildLayout(BuildContext context) → Widget
- Subclasses should override this method to build the layout model.
override
- debugFillProperties(DiagnosticPropertiesBuilder properties) → void
- Add additional properties associated with the node. [...]
override
- build(BuildContext context) → Widget
- Describes the part of the user interface represented by this widget. [...]
inherited
- buildSlivers(BuildContext context) → List<Widget>
- Build the list of widgets to place inside the viewport. [...]
inherited
- buildViewport(BuildContext context, ViewportOffset offset, AxisDirection axisDirection, List<Widget> slivers) → Widget
- Build the viewport. [...]
@protected, inherited
- createElement() → StatelessElement
- Creates a StatelessElement to manage this widget's location in the tree. [...]
inherited
- debugDescribeChildren() → List<DiagnosticsNode>
- Returns a list of DiagnosticsNode objects describing this node's children. [...]
@protected, inherited
- getDirection(BuildContext context) → AxisDirection
- Returns the AxisDirection in which the scroll view scrolls. [...]
@protected, inherited
- noSuchMethod(Invocation invocation) → dynamic
- Invoked when a non-existent method or property is accessed. [...]
inherited
- toDiagnosticsNode({String name, DiagnosticsTreeStyle style }) → DiagnosticsNode
- Returns a debug representation of the object that is used by debugging tools and by DiagnosticsNode.toStringDeep. [...]
inherited
- toString({DiagnosticLevel minLevel: DiagnosticLevel.debug }) → String
- Returns a string representation of this object.
inherited
- toStringDeep({String prefixLineOne: '', String prefixOtherLines, DiagnosticLevel minLevel: DiagnosticLevel.debug }) → String
- Returns a string representation of this node and its descendants. [...]
inherited
- toStringShallow({String joiner: ', ', DiagnosticLevel minLevel: DiagnosticLevel.debug }) → String
- Returns a one-line detailed description of the object. [...]
inherited
- toStringShort() → String
- A short, textual description of this widget.
inherited
Operators
- operator ==(dynamic other) → bool
- The equality operator. [...]
inherited
flutter ListView 页面滚动组件的更多相关文章
- Flutter学习笔记(24)--SingleChildScrollView滚动组件
如需转载,请注明出处:Flutter学习笔记(23)--多 在我们实际的项目开发中,经常会遇到页面UI内容过多,导致手机一屏展示不完的情况出现,以Android为例,在Android中遇到这类情况的做 ...
- 微信小程序 video组件 不随页面滚动
1.页面初始化(滚动前)时,video所在位置 2.页面滚动后,video视频组件所在位置 看了别人家的小程序并不会出现这种状况.最后检查发现,是页面包裹层设置了 height:100% 导致的 顺便 ...
- Android 设置ListView不可滚动 及在ScrollView中不可滚动的设置
http://m.blog.csdn.net/blog/yusewuhen/43706169 转载请注明出处: http://blog.csdn.net/androiddevelop/article/ ...
- RN页面获取组件位置和大小的方法
在RN的页面布局和操作中,有时需要获取元素的大小和位置信息,本文从网上抄袭了几个常用方法,以备不时之需. 首先是获取设备屏幕的宽高 import {Dimensions} from 'react-na ...
- android testview + listview 整体滚动刷新
listview滚动刷新不再讲述怎么实现 因为想实现整体滚动的效果,初始计划scrollView嵌套listview实现. 问题一:scrollview嵌套listview时,listview只能显示 ...
- 页面滚动插件 better-scroll 的用法
better-scroll 是一个页面滚动插件,用它可以很方便的实现下拉刷新,锚点滚动等功能. 实现原理:父容器固定高度,并设置 overflow:hidden,子元素超出父元素高度后将被隐藏,超出部 ...
- vue中监听页面滚动和监听某元素滚动
①监听页面滚动 在生命周期mounted中进行监听滚动: mounted () { window.addEventListener('scroll', this.scrollToTop) }, 在方法 ...
- flutter中的列表组件
列表布局是我们项目开发中最常用的一种布局方式.Flutter 中我们可以通过 ListView 来定义列表项,支持垂直和水平方向展示.通过一个属性就可以控制列表的显示方向.列表有以下分类: 垂直列表 ...
- Flutter 中那么多组件,难道要都学一遍?
在 Flutter 中一切皆是 组件,仅仅 Widget 的子类和间接子类就有 350 多个,整理的 Flutter组件继承关系图 可以帮助大家更好的理解学习 Flutter,回归正题,如此多的组件到 ...
随机推荐
- Wing-AEP平台LWM2M设备接入
实现Wing-AEP中国电信物联网开放平台,LWM2M设备接入 一.准备 接入模组:BC35-G 平台地址:https://www.ctwing.cn/ 点击右上角控制台 点击左侧栏点击产品中心 二. ...
- redis复制机制
摘自redis设计与实现 通过客户端,发送slave of xxx给redis从服务器,即可实现主从服务器之间的复制.如果主服务器设置了requirepass进行身份验证,从服务器需要设置master ...
- R学习笔记3 数据处理
1,日期类型 日期类型比较特殊,日期值通常以字符串的形式输入到R中,然后使用as.Date()函数转换为以数值形式存储的日期变量 mydate <- as.Date("2019-01- ...
- 「LibreOJ NOI Round #2」不等关系
「LibreOJ NOI Round #2」不等关系 解题思路 令 \(F(k)\) 为恰好有 \(k\) 个大于号不满足的答案,\(G(k)\) 表示钦点了 \(k\) 个大于号不满足,剩下随便填的 ...
- [高清] SpringBoot揭秘快速构建微服务体系
------ 郑重声明 --------- 资源来自网络,纯粹共享交流, 如果喜欢,请您务必支持正版!! --------------------------------------------- 下 ...
- ApachShiro 一个系统 两套验证方法-(后台管理员登录、前台App用户登录)同一接口实现、源码分析
需求: 在公司新的系统里面博主我使用的是ApachShiro 作为安全框架.作为后端的鉴权以及登录.分配权限等操作 管理员的信息都是存储在管理员表 前台App 用户也需要校验用户名和密码进行登录.但是 ...
- ICO学习说明
IOC叫做控制反转,可以理解为我要做一件事,分为1,2,3,4这4部,我们可以在一个函数实现这四步,控制反转就是将这个流程体现在框架中.将原来实现在应用程序流程控制转移到框架中,框架利用一个引擎驱动整 ...
- C盘清理、C盘瘦身、省出30G
三招C盘瘦身30G,清理win10系统中虚占C盘空间的三大祸害 1.对C盘进行“磁盘清理” C盘右键->属性->磁盘清理->清理系统文件->勾选“windows更新清理”-&g ...
- 转 C# 使用openssl
//先用大整数来生成一个1024bit的密钥对 RSA rsa = new RSA(); BigNumber number = OpenSSL.Core.Random.Next(10, 10, 1); ...
- springboot笔记05——profile多环境配置切换
前言 一个应用程序从开发到上线,往往需要经历几个阶段,例如开发.测试.上线.每个阶段所用到的环境的配置可能都是不一样的,Springboot 应用可以很方便地在各个环境中对配置进行切换.所以,今天主要 ...