Menu
CoddyTech

区切り線付きの行

CoddyのFlutterジャーニー「リストと画面」セクションの一部。レッスン 8/33。

長いリストは、行と行の間に線があると読みやすくなります。ビルダーを使う場合、Dividerを手作業で記述することはできないため、自動で追加してくれる2つ目の種類のビルダーリストがあります。

ListView.separated(
  itemCount: songs.length,
  itemBuilder: (context, index) {
    return ListTile(title: Text(songs[index]));
  },
  separatorBuilder: (context, index) {
    return const Divider();
  },
)

separatorBuilderは2つの行の間の隙間ごとに呼び出され、その場所に配置するウィジェットを返します。15行のリストには14個の区切りがあり、最後の行の後に区切りが入ることはありません。

区切りには任意のウィジェットを使えます。Dividerや、何もない空間を作るSizedBoxなどです。

challenge icon

チャレンジ

簡単

プレイリストを、2曲ごとにDividerを挟むListView.separatedに変更してください。

自分で試してみよう

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    final List<String> songs = [
      'Morning Light',
      'Paper Planes',
      'City Rain',
      'Slow River',
      'Neon Nights',
      'Golden Hour',
      'Northern Wind',
      'Blue Harbor',
      'Quiet Storm',
      'Summer Static',
      'Echo Valley',
      'Last Train',
      'Silver Lines',
      'Open Road',
      'Starfall',
    ];
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(title: const Text('Playlist')),
        body: ListView.builder(
          itemCount: songs.length,
          itemBuilder: (context, index) {
            return ListTile(title: Text(songs[index]));
          },
        ),
      ),
    );
  }
}
quiz icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

リストと画面のすべてのレッスン

自分で練習してみよう: Flutterオンラインコンパイラ