简体   繁体   中英

How do I sort items in a list by DateTime in Flutter/Dart?

I'm making an app for my Uncle which he asked me to make to challenge me. I thought this was the perfect opportunity to learn Flutter/Dart. I have this code (below), but i need it to organise a list by DateTime (line 77). Each entry has a string id, a DateTime variable , a string name and some body text, at a bare minimum.

import 'package:flutter/material.dart';

import 'package:gym_tracker/model/diary_entry.dart';
import 'package:gym_tracker/utils/store.dart';

class HomeScreen extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => new HomeScreenState();
}

class HomeScreenState extends State<HomeScreen> {
  List<Entry> entries = getEntries();
  List<String> userFavorites = getFavoritesIDs();

  // Inactive widgets are going to call this method to
  // signalize the parent widget HomeScreen to refresh the list view.
  void _handleFavoritesListChanged(String entryID) {
    // Set new state and refresh the widget:
    setState(() {
      if (userFavorites.contains(entryID)) {
        userFavorites.remove(entryID);
      } else {
        userFavorites.add(entryID);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    Column _buildEntries(List<Entry> entriesList) {
      return Column(
        children: <Widget>[
          Expanded(
            child: ListView.builder(
              itemCount: entriesList.length,
              itemBuilder: (BuildContext context, int index) {
                return ListTile(
                  title: Text(entriesList[index].name),
                );
              },
            ),
          ),
        ],
      );
    }

    const double _iconSize = 20.0;

    return DefaultTabController(
      length: 4,
      child: Scaffold(
        appBar: PreferredSize(
          // We set Size equal to passed height (50.0) and infinite width:
          preferredSize: Size.fromHeight(50.0),
          child: AppBar(
            backgroundColor: Colors.white,
            elevation: 2.0,
            bottom: TabBar(
              labelColor: Theme.of(context).indicatorColor,
              tabs: [
                Tab(icon: Icon(Icons.wb_sunny, size: _iconSize)),
                Tab(icon: Icon(Icons.date_range, size: _iconSize)),
                Tab(icon: Icon(Icons.bookmark, size: _iconSize)),
                Tab(icon: Icon(Icons.settings, size: _iconSize)),
              ],
            ),
          ),
        ),
        body: Padding(
          padding: EdgeInsets.all(5.0),
          child: TabBarView(
            // Replace placeholders:
            children: [
              // Display entries today:
              _buildEntries(entries.where((entry) => entry.dateTime.day == DateTime.now().day && entry.dateTime.month == DateTime.now().month && entry.dateTime.year == DateTime.now().year).toList()),
              // Display all entries:
              _buildEntries(entries.where((entry) => ).toList()), //Help Here Please!
              // Display favorite entries:
              _buildEntries(entries.where((entry) => userFavorites.contains(entry.id)).toList()),
              Center(child: Icon(Icons.settings)),
            ],
          ),
        ),
      ),
    );
  }
}

Realistically, this can be done in two ways. One would be to programatically sort the list of entries, while the other would be to get them sorted from wherever you're storing them.

In most situations, I'd argue that it would be better to get the items sorted from the database where you're storing them. And the same goes for just showing the ones from today or the favourites. That depends on which database you're using - but for example, if you're using SQFlite, it would be something like this: db.query(table, orderBy: "column_1 ASC, column_2 DESC"); if column_1 were your date and you wanted oldest to newest. Doing it this way would also allow you to use paging so you're not querying for all of the items in the table at once, which is a good practice if you're dealing with a lot of items.

If there are only a fairly low number of items (most phones should be able to handle <1000 items fairly easily without causing any UI stutter), it's a bit different situation, and doing it on the items straight in dart is a more viable option.

In this case, all you need to do is sort the list based on the date.

To do that, you can call entries..sort((item1, item2) => item1.date.compareTo(item2.date)) assuming .date is the date you're trying to order by. Note that this will sort the same list inline - if you don't want to change the original list, then first make a copy ie List.from(entries)....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM