Home > Enterprise >  Flutter List.generate but in reverse?
Flutter List.generate but in reverse?

Time:03-24

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

CodePudding user response:

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.

  • Related