skip to Main Content

I Have a list that contains some details based on date, like daysummarymodel.

in my app tapping on any date..it should show its summary and that i am using following code

final daySummeryModel=daySummeryList.where((element) => element.dateTime.isSameDate(date)).toList().first;

its working fine but if there is no summary of given date..its showing error like bad state

how to return null if no summary found..so that i can check later if its null nothing to do

class DaySummeryModel
{
  DateTime dateTime;
  int entries;
  double expenseTotal;
  double incomeTotal;

  DaySummeryModel({required this.dateTime,required this.expenseTotal,required this.incomeTotal,required this.entries});

  double get balance=>incomeTotal-expenseTotal;
}

2

Answers


  1. The issue occurs because .first throws an error when the list is empty. Here are a few ways to solve this:

    Using firstOrNull (Recommended for Dart 2.12+):

    final daySummeryModel = daySummeryList
    .where((element) => element.dateTime.isSameDate(date))
    .firstOrNull;
    

    If you’re using an older version of Dart or prefer more explicit control, you can use a different approach:

    final filteredList = daySummeryList
    .where((element) => element.dateTime.isSameDate(date))
    .toList(); 
    final daySummeryModel = filteredList.isNotEmpty ? filteredList.first : null;
    
    Login or Signup to reply.
  2. Please check the list daySummeryList before take first from list :

    final daySummeryModel = daySummeryList.where((element) => element.dateTime.isSameDate(date)).toList();
    
    DaySummeryModel? summary;
    if (daySummeryModel.isNotEmpty) {
      summary = daySummeryModel.first;
    } else {
      summary = null;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search