Bill Tertis
Bill Tertis

Reputation: 207

How to sort months list by current to past? Flutter/Dart

Hello there i have a list with all months, but i want to sort it by current(Octomber) to previous. How can i achieve that?

enter image description here

Here is my code:

Here is my code:

class _HistoryviewState extends State<Historyview> {
List months=[];
  initState() {
    super.initState();
     months =
    ['January', 'February', 'March', 'April', 'May','June','July','August','September','October','November','December'];
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("My History"),
      ),
      body: _buildListView(context) ,


    );
  }
ListView _buildListView(BuildContext context){

    return ListView.builder(itemCount: months.length,
    itemBuilder: (_, index){
      return ListTile(
        title: Text(months[index]),
        subtitle: Text(widget.appController.Totaleachlist[index].toStringAsFixed(3)+'€'),
        leading: Icon(Icons.account_balance_wallet_rounded),
        trailing: Icon(Icons.arrow_forward),
        onTap: (){
          Navigator.push(
            context,
            MaterialPageRoute(builder: (context) => DetailPage(index,widget.appController))
          );
        },
      );
    },
    );
}

Upvotes: 0

Views: 261

Answers (1)

Safwan Parkar
Safwan Parkar

Reputation: 349

I don't think a package or in-built function exists for this.

Try this logic

months = ['January', 'February', 'March', 'April', 'May','June','July','August','September','October','November','December'];

// get current month
var now = new DateTime.now();
var formatter = new DateFormat('MM');
String month = formatter.format(now);  // this will return '10' for October

for (int i=month; i>=1; i--){
   // loop through the months list backwards
   // do your ListView functions
}

Upvotes: 2

Related Questions