乐闻世界logo
搜索文章和话题

How can I add divider between each List Item in my code in Flutter?

1个答案

1

Adding separators between list items in Flutter can typically be achieved using the ListView.separated constructor. This constructor allows you to define how to build the list items (itemBuilder) and the separators (separatorBuilder). Below, I'll demonstrate how to use this method with an example.

Suppose we have a simple list of strings, and we want to add dividers between each element of the list.

dart
import 'package:flutter/material.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: Text("ListView.separated Example"), ), body: MyListView(), ), ); } } class MyListView extends StatelessWidget { final List<String> items = ["苹果", "香蕉", "橙子", "西瓜", "葡萄"]; Widget build(BuildContext context) { return ListView.separated( itemCount: items.length, itemBuilder: (context, index) { return ListTile( title: Text(items[index]), ); }, separatorBuilder: (context, index) { return Divider(); }, ); } }

In the above code, we define a MyListView widget that uses ListView.separated to generate the list. itemBuilder is responsible for building each list item, while separatorBuilder handles the separators between items, where we use Divider as the separator.

This approach makes adding separators between list items very simple and flexible, while also keeping the code clean and easy to manage. You can customize the appearance and behavior of the separators by modifying separatorBuilder, for example, by adjusting the height, color, or adding spacing.

2024年8月8日 00:35 回复

你的答案