What is the way to use 2 arrays in a listview.builder in flutter

Viewed 85

I have 2 arrays and I want to put them in one Listview.builder so that they scroll together. (The first array item appears and when you scroll more you arrive to the second array), each one should have a header before its items. I tried to put them in 2 listviews but the screen got divided and the scene was horrible.

2 Answers

If you are interested using ListView.builder

class ListTest2 extends StatelessWidget {
  const ListTest2({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final list1 = List.generate(4, (i) => "list1 i $i");
    final list2 = List.generate(4, (i) => "list2 i $i");

    final combineList = [...list1, ...list2];
    return Scaffold(
      body: ListView.builder(
          itemCount: combineList.length,
          itemBuilder: (context, index) {
            if (index == 0 && list1.isNotEmpty) {
              return Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text("header of List 1"),
                  Text(combineList[index]),
                ],
              );
            }

            if (index == list1.length && list2.isNotEmpty) {
              return Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text("header of List 2"),
                  Text(combineList[index]),
                ],
              );
            }

            return Text(combineList[index]);
          }),
    );
  }
}

Or You can do it like

return Scaffold(
  body: ListView(
    children: [
      Text("List1 header  "),
      ...list1.map((e) => Text(e)),
      Text("List2 header "),
      ...list2.map((e) => Text(e)),
    ],
  ),
);

If you like to ignore header on empty case,

@override
Widget build(BuildContext context) {
  final list1 = List.generate(4, (i) => "list1 i $i");
  final list2 = List.generate(4, (i) => "list2 i $i");

  return Scaffold(
    body: ListView(
      children: [
        if (list1.isNotEmpty) Text("List1 header  "),
        ...list1.map((e) => Text(e)),
        if (list2.isNotEmpty) Text("List2 header "),
        ...list2.map((e) => Text(e)),
      ],
    ),
  );
}

You can combine the arrays into a single array before passing to the ListView's children:

ListView(
    ...
    children: <Widget>[
        Text("array1 header"),
        ...array1,
        Text("array2 header"),
        ...array2,
    ],
    ...
)
Related