點燈坊

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

ListView 顯示垂直清單

Sam Xiao's Avatar 2024-11-30

ListView 適合顯示垂直清單,且支援卷軸。

Version

Flutter 3.24

Flutter

overview01

  • 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():產生 item1item 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

  • ListViewListTile 會成對一起使用