Home > front end >  What is the way to use 2 arrays in a listview.builder in flutter
What is the way to use 2 arrays in a listview.builder in flutter

Time:07-22

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 arive 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.

CodePudding user response:

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)),
      ],
    ),
  );
}

CodePudding user response:

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