如何从列表中获取数据表从开始日期到结束日期的行?

How can I get the rows of a datatable from start date to the end date from the List?

我想根据开始日期和结束日期获取数据行table。

假设我的开始日期是“2015-09-08”,结束日期是“2015-10-08”。

基于这些日期,我想要使用 flutter 的数据行 table。我想要使​​用以下列表的开始日期和结束日期之间的日期。

 final List<UserView> _usersViewData = [
    UserView(
        date: '2021-08-01', //yyyy-mm-dd
        description: 'Product Ordered',
        amount: 1002.00,
        status: '0'),
   
    UserView(
        date: '2021-08-10',
        description: 'Product Ordered',
        amount: 890.12,
        status: '1'),
   
    UserView(
        date: '2021-09-04',
        description: 'Product Ordered',
        amount: 189.14,
        status: '0')..........];

          late DateTime from = DateTime.now();
          late DateTime to = DateTime.now();

        Future<void> _selectDate(BuildContext context, int i) async {
        final DateTime? pickedDate = await showDatePicker(
        context: context,
        initialDate: DateTime.now(),
        firstDate: DateTime(2015),
        lastDate: DateTime(2050));
        if (pickedDate != null) {
         if (i == 0) {
         setState(() {
          from = pickedDate;
        });
      } else if (i == 1) {
        setState(() {
          to = pickedDate;
        });
      }
    }
  }

我想使用上面的用户视图列表获取基于开始日期和结束日期的行列表。 我试过很多东西喜欢

  final int difference = from.difference(to).inDays;
  //and also tried compare

  _usersViewData.sort((a, b) => a.date.compareTo(b.date));

我想使用上面的用户视图列表获取基于开始日期和结束日期的行列表。

您可以使用 DateTime class 方法和 where 方法来实现:

final views = _usersViewData.where((user) {
    final currentDate = DateTime.tryParse(user.date);
    return currentDate != null 
      && (currentDate.isAfter(from) || currentDate.isAtSameMomentAs(from)) 
      && (currentDate.isBefore(to) || currentDate.isAtSameMomentAs(to));
}).toList();

使用以下代码过滤给定范围内的列表。 tofrom 从日期选择器初始化的 DateTime 对象。

List<UserView> temp = list.where((obj){
    return DateTime.parse(obj.date).compareTo(from) >= 0 && 
      DateTime.parse(obj.date).compareTo(to) <=0;
  }).toList();
  

Compares this DateTime object to [other], returning zero if the values are equal.

Returns a negative value if this DateTime [isBefore] [other]. It returns 0 if it [isAtSameMomentAs] [other], and returns a positive value otherwise (when this [isAfter] [other]).