Bad State No Element Found in Flutter
Bad state no element found error in flutter#
This error usually comes in flutter when you are using firstWhereOrNull()
function on List of data
for example look the below code.
class Person{
Person({required this.name,required this.age});
String name;
int age;
}
List<Person> persons = [
Person(name: "John", age:12 ),
Person(name: "Denver", age:13)
];
var found = persons.firstWhere((e)=> e.age == 2);
in the above code if where condition doesn’t find any data matching age =2 then it will give you Bad state no element found error
. for avoiding this error you can add orElse
parameter which will return if element not found.
like below
Expected solution#
List<Person?> persons = [
Person(name: "John", age:12 ),
Person(name: "Denver", age:13)
];
var found = persons.firstWhere((e)=> e?.age == 2, orElse: ()=> null);
but for this solution to work you have to modify the input source for null safety. This is not good if you donot have access to modify the src data then how will you handle this error.
Best soultion#
you can simply implement your own method which will loop through and return based on your condition or there is already prebuild solution in package collection
import 'package:collection/collection.dart';
List<Person> persons = [
Person(name: "John", age:12 ),
Person(name: "Denver", age:13)
];
var found = persons.firstWhereOrNull((e)=> e.age == 2);
In this way you do not need to modify the source input data. It will just work and return null if no data found.