How To Reverse List In Flutter – Easy Flutter Code Example

reverse list in flutter

In this tutorial, we’ll learn how to reverse list in Flutter. We’ll be using multiple Flutter code examples to demonstrate it practically.

After reading this post, you’ll have a detailed practical knowledge of how to easily reverse list in Flutter.

So without any delay, let’s just dive right into its practical implementation.

What is Reverse List In Flutter?

It specifies reversing the order of items in Flutter list. It means the updated list will start from the last item, then the second last one and so on until it reaches the first item.

Let’s now practically understand it using proper Flutter code examples.

Implementing Reverse List in Flutter (Easy Examples)

Below examples will demonstrate how to reverse the order of items in Flutter list.

Example 1: Reverse a Simple List

List simpleList=[1,2,3,4,5,6];
print(simpleList.reversed.toList());

Output

[6, 5, 4, 3, 2, 1]

As you can see, we have used the reversed method and as a result, a reversed list is returned. Use the toList() method to return it as a list as specified in above code. See another example below:

List simpleList=[1,2,4,3,5,'green', 45, 6,[3,4,5]];
print(simpleList.reversed.toList());

Output

[[3, 4, 5], 6, 45, green, 5, 3, 4, 2, 1]

As you can see here, the order of nested list is not changed as it is used as a single item.

Example 2: Reverse Method Returns Updated List

The reverse method does not update the current list. It returns a new reversed list. See below code:

List simpleList=[1,2,4,3,5,'green', 45, 6,[3,4,5]];

print(simpleList.reversed.toList()); // returns a new reversed list
print(simpleList);                  // original list

Output

[[3, 4, 5], 6, 45, green, 5, 3, 4, 2, 1]  //new reversed list returned

[1, 2, 4, 3, 5, green, 45, 6, [3, 4, 5]]  // original list(not reversed)
You can pass the updated list to a new list. See below code:
List simpleList=[1,2,4,3,5,'green', 45, 6,[3,4,5]];
List newList=simpleList.reversed.toList(); // returned list is assigned to a new empty list
print(newList);

Output

[[3, 4, 5], 6, 45, green, 5, 3, 4, 2, 1]

So this is how we can easily reverse list in Flutter. Hope you have learned alot from this tutorial. Do give this method a try and share your experience with us and other Flutter developers.

Conclusion

To conclude, hope you now have a proper and detailed practical knowledge of how to reverse list in Flutter. I’ll be happy to receive your feedback on this post.

I’d also strongly recommend my other articles for you to visit. Thank you for reading this post.

Leave a Comment

Your email address will not be published. Required fields are marked *