Flutter group listviews with separator

Viewed 54599

I am looking for some guidance to create listviews with separators. For instance, I would like to take messages from a DB grouped by date and separate the messages by date with some graphic or line, etc... and then have the messages under the separator. Trying this in flutter and any guidance or push in the right direction would be appreciated.

7 Answers

I apologize for the ugliness of the design, but just to show you, you can pretty much build your own design that you desire, this a quick example:

enter image description here

import "package:flutter/material.dart";
import 'package:meta/meta.dart';

class Test extends StatefulWidget {
  @override
  _TestState createState() => new _TestState();
}

class _TestState extends State<Test> {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text("Test"),
      ),
      body: new ListView.builder(
        // itemCount: myData.lenght(),
          itemCount: 20,
          itemBuilder: (BuildContext context, int index) {
            //sort my data by timestamp before building
            return new CustomWidget(date: "Convert my time stamp to date",
              content: "My Awesome Content",
              trailingIconOne: new Icon(Icons.share, color: Colors.blueAccent,),
              trailingIconTwo: new Icon(
                Icons.favorite, color: Colors.redAccent,),);
          }),
    );
  }
}

class CustomWidget extends StatelessWidget {
  String date;
  String content;

  Icon trailingIconOne;

  Icon trailingIconTwo;

  CustomWidget(
      {@required this.date, @required this.content, @required this.trailingIconOne, @required this.trailingIconTwo});

  @override
  Widget build(BuildContext context) {
    return new Container(
      decoration: new BoxDecoration(
          border: new Border.all(color: Colors.grey[500])
      ),
      child: new Column(
        children: <Widget>[
          new Container (child: new Text(date), color: Colors.yellow[200],),
          new Container(height: 15.0,),
          new Text(content),
          new Row(
            mainAxisAlignment: MainAxisAlignment.end,
            children: <Widget>[
              new IconButton(icon: trailingIconOne, onPressed: () {}),
              new Container(width: 10.0,),
              new IconButton(icon: trailingIconTwo, onPressed: () {})
            ],
          )
        ],
      ),
    );
  }
}

For a better design, you can get rid of the borders and use a Divider instead:

return new Container(
      child: new Column(
        children: <Widget>[
          new Column (children: <Widget>[
            new Container (child: new Text(date), color: Colors.yellow[200],),
            new Container(height: 15.0,),
            new Text(content),
            new Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: <Widget>[
                new IconButton(icon: trailingIconOne, onPressed: () {}),
                new Container(width: 10.0,),
                new IconButton(icon: trailingIconTwo, onPressed: () {}),
          ], ),

              new Divider(height: 15.0,color: Colors.red,),
            ],
          )
        ],
      ),

And a better visual solution in my opinion is to use a Card instead of Container,

return new Card(
      child: new Column(
        children: <Widget>[
          new Column (children: <Widget>[
            new Container (child: new Text(date), color: Colors.yellow[200],),
            new Container(height: 15.0,),
            new Text(content),
            new Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: <Widget>[
                new IconButton(icon: trailingIconOne, onPressed: () {}),
                new Container(width: 10.0,),
                new IconButton(icon: trailingIconTwo, onPressed: () {}),
          ], ),

            //  new Divider(height: 15.0,color: Colors.red,),
            ],
          )
        ],
      ),
    );

A much cleaner and simple solution would be to use the following

ListView.separated(
  separatorBuilder: (context, index) => Divider(
        color: Colors.black,
      ),
  itemCount: 20,
  itemBuilder: (context, index) => Padding(
        padding: EdgeInsets.all(8.0),
        child: Center(child: Text("Index $index")),
      ),
)

Long answer short

Just use Column and add Divider

ListView.builder(
      itemCount: count,
      itemBuilder: (context, int index) {return tile(index);},
    ),

Create a widget for itemBuilder

Widget tile(int index) {
return Column(
  children: <Widget>[
    // your widgets in listView
    Divider(),    //at last simply add divider
  ],
);

}

While this might not be applicable to your situation, a simple way to add dividers to a ListView is to use ListView.divideTiles:

// Adapted from https://flutter.io/flutter-for-android/#listviews--adapters

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new ListExamplePage(),
    );
  }
}

class ListExamplePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // https://docs.flutter.io/flutter/material/ListTile/divideTiles.html
    var dividedWidgetList = ListTile.divideTiles(
        context: context,
        tiles: _getListData(),
        color: Colors.black).toList();

    return new Scaffold(
      appBar: new AppBar(
        title: new Text('List Example'),
      ),
      body: new ListView(children: dividedWidgetList)
    );
  }

  _getListData() {
    List<Widget> widgets = [];
    for (int i=0; i<100; i++) {
      widgets.add(
        new Padding(
            padding: new EdgeInsets.all(10.0),
            child: new Text('Row $i'))
      );
    }
    return widgets;
  }
}

EDIT:

For dynamically built lists, ListTile.divideTiles isn't the right choice. Adding a divider at the stage where the list item is built is probably the best way to go:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new ListExamplePage(),
    );
  }
}

class ListExamplePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
        appBar: new AppBar(
          title: new Text('List Example'),
        ),
        body: new ListView.builder(
          itemBuilder: (BuildContext context, int position) =>
              // Try using either _getRowWithDivider or _getRowWithBoxDecoration
              // for two different ways of rendering a divider
              _getRowWithDivider(position),
        ));
  }

  /// Returns the widget at position i in the list, separated using a divider
  Widget _getRowWithDivider(int i) {
    var children = <Widget>[
      new Padding(padding: new EdgeInsets.all(10.0), child: new Text('Row $i')),
      new Divider(height: 5.0),
    ];

    return new Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: children,
    );
  }

// Returns the widget at position i in the list, separated using a BoxDecoration
  Widget _getRowWithBoxDecoration(int i) {
    return new Container(
        decoration: new BoxDecoration(
            border:
                new Border(bottom: new BorderSide(color: Colors.grey[100]))),
        child: new Padding(
            padding: new EdgeInsets.all(10.0), child: new Text('Row $i')));
  }
}

A lot of overly complex answers here

Just use divideTiles:

new ListView(
              children: ListTile.divideTiles(context: context, tiles:

Or alternatively use separated:

new ListView.separated(
              itemCount: 25,
              separatorBuilder: (BuildContext context, int index) => Divider(),
              itemBuilder: (BuildContext context, int index) {
final Iterable<ListTile> products = widget.products.map((Product product) {
  return productListAdapter(
    product: product,
  ).build(context);
});

final listView = ListTile.divideTiles(
        context: context, tiles: products, color: Colors.black12)
    .toList();

return ListView(
    padding: EdgeInsets.symmetric(vertical: 8.0), children: listView);

productListAdapter code is here

class productListAdapter extends StatelessWidget {
   final Product product;  
   productListAdapter({this.product});

   TextStyle getTextStyle() {
       return TextStyle(
           fontSize: 16.0,
           color: Colors.black);
   }

   Color getColor(BuildContext context) {
       return Theme.of(context).primaryColor;
     }
   }

   @override
   Widget build(BuildContext context) {
     return ListTile(
       title: Text(product.name),
       leading: CircleAvatar(
         child: Text(
           product.name[0],
           style: getTextStyle(),
         ),
         backgroundColor: getColor(context),
       ),
     );
   }
 }
Related