《Web 开发者如何理解 Flutter 布局》
本系列旨在帮助 Web 前端开发者更好的理解 Flutter 的布局组件,只做对应的语法映射描述和最基本的技术说明。
列表视图及滚动条。
-
通过 SingleChildScrollView (单个子组件滚动视图) 创建滚动视图
-
通过 ListView(列表视图) 创建滚动视图
-
通过 Scrollbar(滚动条) 创建滚动条
-
通过 Axis(坐标轴) 指定滚动方向
1、使用 SingleChildScrollView 创建滚动视图
在 web 应用中, 当 body 中内容的宽高大于屏幕本身宽高时,页面会被撑开并附加滚动条。
而在原生 app 中并不具备这个效果,即使页面中本身的内容超出了屏幕, 应用容器也不会为你添加滚动容器及滚动条。
因此, 我们需要使用 Widget 来构造他们。
- *下列示例中使用了解析器中预存的颜色常量,其中 web 应用使用安全色, 而原生应用使用 Google Material Design 设计规范中的颜色实现, 因此它们可能在展现上有所差异。
在后续的例子中依旧可能会有这种情况出现。 如果您阅读至此提示到之后的章节, 除非另有说明, 我们认为您已经知晓并认可这些差异, 后续将不再针对这类差异性单独进行赘述说明。*
SingleChildScrollView(
Column(
children: <Widget>[
Container(
color: Colors.red,
height: 600
),
Container(
color: Colors.blue,
height: 600
)
]
)
)
等效于:
<div
style=
"overflow-y: scroll;"
>
<div style=
"
height: 600px;
background-color: red;
"
></div>
<div style=
"
height: 600px;
background-color: blue;
"
></div>
</div>
2、使用 ListView + Scrollbar 构建带有滚动条的可滚动长列表
你可以为页面中的部分内容添加 Scrollbar 以显示滚动条, 同时如果你希望区域可被滚动,你需要将他们包裹在ListView内,它会帮你创建可滚动的容器。
ListView(
//纵向(vertical) 为 ListView 默认的滚动方向,此行可选 👇
scrollDirection: Axis.vertical,
//纵向(vertical) 为 ListView 默认的滚动方向,此行可选 👆
children: [
Container(
height: 700,
color: Colors.lightBlue
),
Container(
height: 700,
color: Colors.green
),
Container(
height: 700,
color: Colors.orange
)
]
)
等效于:
<div
style=
"overflow-y: scroll;"
>
<div style=
"
height: 700px;
background-color: lightBlue;
"
></div>
<div style=
"
height: 700px;
background-color: green;
"
></div>
<div style=
"
height: 700px;
background-color: orange;
"
></div>
</div>
3、构建横向滚动区域
ListView(
//滚动方向: 允许沿横向(horizontal) 坐标轴滚动
scrollDirection: Axis.horizontal,
children: [
Container(
width: 400,
color: Colors.lightBlue
),
Container(
width: 400,
color: Colors.green
),
Container(
width: 400,
color: Colors.orange
)
]
)
等效于:
<div
style=
"overflow-x: scroll;"
>
<div style=
"
width: 400px;
background-color: lightBlue;
"
></div>
<div style=
"
width: 400px;
background-color: green;
"
></div>
<div style=
"
width: 400px;
background-color: orange;
"
></div>
</div>
相比 SingleChildScrollView 创建的滚动视图而言,如果你需要惰性加载,使用 ListView 有更加明显的性能优势。