Home > Mobile >  Futter/dart: [ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: Bad state: No element
Futter/dart: [ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: Bad state: No element

Time:08-16

 getActivitiesResponseModel!.activities!
        .where((element) => element.status == "Pending")
        .first

when there is not found any item related to above faltering than throw bad state exception. I have searched but orElse: () => null callback is not defined for where function and i need only single object.so what i should do to handle this Exception

CodePudding user response:

Your exception raising because of .first method, that have to return single object from list. In your case, there might be no elements by filtering, then, you should check, if your list isn't empty, like that.

Object? _searchitem;
var filteredList = getActivitiesResponseModel!.activities!
        .where((element) => element.status == "Pending");
    if (filteredList.isNotEmpty)
    {
    _searchitem = filteredList.first;
    }
        

Or, you can also use .firstWhere(), where you need to define orElse funct to handle errors.

getActivitiesResponseModel!.activities!
        .firstWhere((element) => element.status == "Pending", orElse: () => null);

CodePudding user response:

 getActivitiesResponseModel!.activities!

This is a very bad usage. You need to make sure this datas are not null.

if(getActivitiesResponseModel != null) 
 { 
   if(getActivitiesResponseModel!.activities != null){
     getActivitiesResponseModel!.activities!
        .where((element) => element.status == "Pending")
        .first
}}

Can you try like this?

CodePudding user response:

 { 
   if(getActivitiesResponseModel!.activities != null){
     getActivitiesResponseModel!.activities!
        .where((element) => element.status == "Pending")
        .first
}}```
  • Related