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

Issue

I want to get the rows of a data table based on the start date and end date.

Suppose my start date is ‘2015-09-08’ and end date is ‘2015-10-08’.

Based on these dates, I want the rows of a data table using flutter. I want the dates between the start date and end date using the below list.

 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;
        });
      }
    }
  }

enter image description here

I want to get the list of rows based on the start date and end date using the above user view list.
I have tried many things likes

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

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

I want to get the list of rows based on the start date and end date using the above user view list.

Solution

You can use DateTime class methods and where method to achieve that:

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();

Answered By – Yair Chen

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published