ListView
適合顯示垂直清單,且支援卷軸。
Version
Flutter 3.24
Flutter
- Android 與 iOS 都成功使用
ListView
實現清單
ListView
import 'package:flutter/material.dart';
class Home extends StatefulWidget {
const Home({super.key});
State<Home> createState() => _HomeState();
}
class _HomeState extends State<Home> {
final List<String> _data = List.generate(
3,
(index) => 'Item ${index + 1}',
);
Widget build(BuildContext context) {
var appBar = AppBar(
title: const Text('ListView'),
);
var listView = ListView.builder(
itemCount: _data.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(
_data[index],
),
onTap: () {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
_data[index],
),
),
);
},
);
},
);
return Scaffold(
appBar: appBar,
body: listView,
);
}
}
Line 11
final List<String> _data = List.generate(
3,
(index) => 'Item ${index + 1}',
);
List.generate()
:產生item1
到item 3
的假資料
Line 30
var listView = ListView.builder(
itemCount: _data.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(
_data[index],
),
onTap: () {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
_data[index],
),
),
);
},
);
},
);
ListView.builder()
:由itemBuilder
產生ListView
itemCount
:設定 ListView 筆數itemBuilder()
:建立ListTile
ListTile
:顯示清單中每筆項目title
:設定顯示文字onTap()
:當點擊項目時觸發
Conclusion
ListView
與ListTile
會成對一起使用