建立一個網格清單
有時候,你可能希望用網格來展示內容,而不是一條接著一條的普通清單來展示。在本文當中,我們將採用 GridView
widget。
用網格展示資料最簡單的方式,就是透過使用 GridView.count()
構造方法,因為它允許我們指定有多少行多少列。
為了幫助我們想象 GridView
是如何工作的,在這個例子中,我們將建立一個包含有 100 個 widget 的 List,每個 Widget 將展示它在 List 中的索引。
GridView.count(
// Create a grid with 2 columns. If you change the scrollDirection to
// horizontal, this produces 2 rows.
crossAxisCount: 2,
// Generate 100 widgets that display their index in the List.
children: List.generate(100, (index) {
return Center(
child: Text(
'Item $index',
style: Theme.of(context).textTheme.headlineSmall,
),
);
}),
),
互動式範例
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
const title = 'Grid List';
return MaterialApp(
title: title,
home: Scaffold(
appBar: AppBar(
title: const Text(title),
),
body: GridView.count(
// Create a grid with 2 columns. If you change the scrollDirection to
// horizontal, this produces 2 rows.
crossAxisCount: 2,
// Generate 100 widgets that display their index in the List.
children: List.generate(100, (index) {
return Center(
child: Text(
'Item $index',
style: Theme.of(context).textTheme.headlineSmall,
),
);
}),
),
),
);
}
}