Flutter List.generate but in reverse?
Asked Answered
E

1

1

I have a container that I am trying to print out items form a list, minus the last item in the list. I am using list.generate:

        child: Container(
          width: double.infinity,
          color: Colors.white,
          child: ListView(
            padding: const EdgeInsets.only(top: 10.0),
            children: List.generate(
              Provider.of<WeekList>(context).listOfWeeks.toList().length -
                  1,
              (index) => ListTileCustom(
                index: index,
              ),
            ),
          ),
        ),

My problem is when it prints out my custom ListTileCustom widget each new item added to the list is added to the bottom and not the top in the view.

enter image description here

In the picture above the order should be:

  • Red Bar
  • Red / Green Bar
  • Green bar

and when I add new items by pressing the button they should be added to the top not the bottom.

I tried adding reverse: true and that gets the order right but moves everything to the bottom and adds a ton of white space above them... Also not sure the scroll will work in the right direction at that point either.

enter image description here

Escalera answered 23/3, 2022 at 23:12 Comment(0)
W
6

To reverse a list in Dart, you can use ..reversed method. In the code you posted, that would be: children: List.generate(/* omitted */).reversed.toList().

Another (probably better) solution is to use for loop directly in children, for example:

ListView(
  children: [
    for (int i = 0; i < 5; i++) FlutterLogo(),
  ],
)

With this approach you can easily invert the list (and omit one element, like you desired) by changing the loop, e.g. for (int i = 10; i > 1; i--) or something.

Windsail answered 23/3, 2022 at 23:42 Comment(1)
thanks so much the for loop worked great. I had to tweak the loop just a little for my needs but it pointed me in the right direction!Escalera

© 2022 - 2024 — McMap. All rights reserved.