Bad state: No element

Viewed 2258

i just want to know what is that for? and when it is coming, is it API problem?

         BlocBuilder<OrderBloc, OrderState>(
                  builder: (context, finalstate) {
                    if (state is OrderLoaded) {
                      for (var item in state.orderSent) {
                        totalweightsforsent.add(item.totalWeight);
//right here when i fetch the data from API and when it is done it is not going forward anymore
                      }
                      for (var item in state.orderPackaging) {
                        totalforpacking.add(item.totalWeight);
                      }
2 Answers

No, its not an API problem, it is there for some reason

Let's look at the example of firstWhere which gets the color string from the list

InValid Color String

void main() {
  List<String> list = ['red', 'yellow', 'pink', 'blue'];
  var newList = list.firstWhere((element) => element.contains('green'), 
      orElse: () => 'No matching color found');
  print(newList);
}

Output:

No matching Color found

Valid Color String

 void main() {
      List<String> list = ['red', 'yellow', 'pink', 'blue'];
      var newList = list.firstWhere((element) => element.contains('blue'), 
          orElse: () => 'No matching color found');
      print(newList);
    }

Output:

blue

Above, all are valid cases but if orElse() block gets missing there it will throw BadStateException

void main() {
  List<String> list = ['red', 'yellow', 'pink', 'blue'];
  var newList = list.firstWhere((element) => element.contains('green'));
  print(newList);
}

Output:

[VERBOSE-2:ui_dart_state.cc(171)] Unhandled Exception: Bad state: No element

Another way of seeing this error is to access properties like first or last of an empty list, for example:

final myList = [];
print(myList.first);

The solution is to always do length > 0 check before accessing related list properties, eg using isNotEmpty property:

final myList = [];
if (myList.isNotEmpty) {
  print(myList.first);
}
Related