點燈坊

失くすものさえない今が強くなるチャンスよ

GridView 顯示水平清單 (Count)

Sam Xiao's Avatar 2024-11-28

GridView 適合顯示水平清單,且自動根據目前寬度換行。

Version

Flutter 3.24.5

Flutter

count01

  • 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():建立 GridView
    • crossAxisCount:設定橫軸顯示個數
    • mainAxisSpacing:設定縱軸間距
    • crossAxisSpacing:設定橫軸間距
    • childAspectRatio:設定項目的長寬比例
    • children:設定子項目

GridViewmainAxis縱軸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 設定橫軸顯示個數