简体   繁体   English

如何在Flutter / Dart中按DateTime对列表中的项目进行排序?

[英]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. 我认为这是学习Flutter / Dart的绝佳机会。 I have this code (below), but i need it to organise a list by DateTime (line 77). 我有下面的代码,但是我需要它通过DateTime来组织列表(第77行)。 Each entry has a string id, a DateTime variable , a string name and some body text, at a bare minimum. 每个条目至少都有一个字符串ID,一个DateTime变量,一个字符串名称和一些正文。

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"); 这取决于您使用的数据库-但是例如,如果您使用的是SQFlite,则可能是这样的: db.query(table, orderBy: "column_1 ASC, column_2 DESC"); if column_1 were your date and you wanted oldest to newest. 如果column_1是您的日期,并且您想从最早到最新。 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. 如果物品数量很少(大多数手机应该能够轻松处理<1000个物品而不会导致UI停顿),情况就有些不同了,直接在飞镖上放置物品是一个更可行的选择。

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. 为此,您可以调用entries..sort((item1, item2) => item1.date.compareTo(item2.date))假设.date是您要订购的日期。 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).... 请注意,这将对同一列表进行内联排序-如果您不想更改原始列表,请首先进行复制,即List.from(entries)....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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