跳到主內容

建立網格列表

如何實現網格列表。

在某些情況下,你可能希望以網格形式顯示專案,而不是以一個接一個的普通列表形式顯示。要完成此任務,請使用 GridView 元件。

開始使用網格最簡單的方法是使用 GridView.count() 建構函式,因為它允許你指定想要的行數或列數。

為了直觀地瞭解 GridView 的工作原理,我們可以生成一個包含 100 個元件的列表,並在列表中顯示它們各自的索引。

dart
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: TextTheme.of(context).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: TextTheme.of(context).headlineSmall,
              ),
            );
          }),
        ),
      ),
    );
  }
}