[英]how to enable scrolling when ListView widget reach at top in flutter
為了解釋我想要什么,我創建了一個簡單的演示文件
這里我有 4 個容器,
我想要的是,當我向上滾動時,所有三個容器(紅色、綠色和列表視圖)都應該向上滾動,當列表視圖到達頂部(歡迎容器下方)時,它的滾動應該開始......
class HomeScreen extends StatelessWidget {
HomeScreen({Key? key}) : super(key: key);
List<String> mydata = [];
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Column(
children: [
//this welcome container should be fixed at top
Container(height: 50, child: Center(child: Text('Welcome'))),
Container(
height: 100,
color: Colors.red,
),
Container(
height: 200,
color: Colors.green,
),
Expanded(
child: ListView.builder(
itemCount: mydata.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(mydata[index]),
leading: CircleAvatar(),
);
}))
],
),
),
);
}
}
您可以將itemCount
增加 2。
body: SafeArea(
child: Column(
children: [
Container(height: 50, child: Center(child: Text('Welcome'))),
Expanded(
child: ListView.builder(
itemCount: mydata.length + 2,
itemBuilder: (context, index) {
if (index == 0) {
return Container(
height: 100,
color: Colors.red,
);
}
if (index == 1) { // you can just merge it with if like `index<2`, then use condition
return Container(
height: 200,
color: Colors.green,
);
}
return ListTile(
title: Text(mydata[index - 2]),
leading: CircleAvatar(),
);
}))
],
),
),
另外我會建議你檢查CustomScrolView
。
為了在 ListView 小部件到達頂部時啟用滾動,並讓其他容器隨之滾動,您可以將整個列包裝在 SingleChildScrollView 小部件中。 SingleChildScrollView 允許您滾動整個列,包括歡迎容器、紅色容器、綠色容器和 ListView。
下面是一個示例,說明如何修改代碼以在 ListView 小部件到達頂部時啟用滾動:
return Scaffold(
body: SafeArea(
child:SingleChildScrollView(
child: Column(children: [
//this welcome container should be fixed at top
Container(
height: 50,
child: Center(child: Text('Welcome'))),
Container(
height: 100,
color: Colors.red,
),
Container(
height: 200,
color: Colors.green,
),
Expanded(child: ListView.builder(
itemCount: mydata.length,
itemBuilder: (context,index){
return ListTile(
title: Text(mydata[index]),
leading: CircleAvatar(),
);
}))
],),
),
),
);
通過將列包裝在 SingleChildScrollView 中,當您向上滾動時,所有三個容器(RED、GREEN 和 ListView)都將向上滾動,當 ListView 到達頂部(歡迎容器下方)時,它的滾動將開始。
或者,您可以使用 ListView 小部件並將 physics 屬性設置為 NeverScrollableScrollPhysics 以防止 ListView 滾動。
Expanded(
child: ListView.builder(
physics: NeverScrollableScrollPhysics(),
itemCount: mydata.length,
itemBuilder: (context,index){
return ListTile(
title: Text(mydata[index]),
leading: CircleAvatar(),
);
}
)
)
這種方法將允許父 Scrollview 向上滾動,當 ListView 到達頂部時,將看到 Welcome 容器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.