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

Time:09-30

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.

CodePudding user response:

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(startDate) && currentDate.isBefore(endDate);
}).toList();

CodePudding user response:

User the following code to filter the list on the given range. to and from the DateTime objects initialized from date picker.

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]).

  • Related