GridView
適合顯示水平清單,且自動根據目前寬度換行。
Version
Flutter 3.24.5
Flutter
- Android 與 iOS 都成功使用
GridView.count()
實現水平清單
GridView
import 'package:flutter/material.dart';
class Home extends StatefulWidget {
const Home({super.key});
State<Home> createState() => _Home();
}
class _Home extends State<Home> {
final List<String> _data = List.generate(
8,
(index) => 'Item ${index + 1}',
);
Widget build(BuildContext context) {
var appBar = AppBar(
title: const Text('GridView.count'),
);
var gridView = GridView.count(
crossAxisCount: 2,
mainAxisSpacing: 8.0,
crossAxisSpacing: 8.0,
childAspectRatio: 2,
children: _data.map(
(item) {
return Container(
alignment: Alignment.center,
decoration: BoxDecoration(
color: Colors.blue,
borderRadius: BorderRadius.circular(8),
),
child: Text(
item,
style: const TextStyle(
color: Colors.white,
),
),
);
},
).toList(),
);
var body = Padding(
padding: const EdgeInsets.all(8.0),
child: gridView,
);
return Scaffold(
appBar: appBar,
body: body,
);
}
}
Line 11
final List<String> _data = List.generate(
8,
(index) => 'Item ${index + 1}',
);
List.generate()
:產生 8 筆 List 假資料
Line 22
var gridView = GridView.count(
crossAxisCount: 2,
mainAxisSpacing: 8.0,
crossAxisSpacing: 8.0,
childAspectRatio: 2,
children: gridTile,
);
GridView.count()
:建立 GridViewcrossAxisCount
:設定橫軸顯示個數mainAxisSpacing
:設定縱軸間距crossAxisSpacing
:設定橫軸間距childAspectRatio
:設定項目的長寬比例children
:設定子項目
GridView
的mainAxis
為縱軸
,crossAxis
為橫軸
Line 22
var gridView = GridView.count(
children: _data.map(
(item) {
return Container(
alignment: Alignment.center,
decoration: BoxDecoration(
color: Colors.blue,
borderRadius: BorderRadius.circular(8),
),
child: Text(
item,
style: const TextStyle(
color: Colors.white,
),
),
);
},
).toList(),
)
map()
:將 List 轉成 GridView 的子項目
Conclusion
- 當使用
GridView.count()
建立GridView
時,一定要設定crossAxisCount
設定橫軸顯示個數