Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bad state: No element

Tags:

flutter

dart

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);
                      }
like image 883
Yahya Parvar Avatar asked Jul 07 '26 02:07

Yahya Parvar


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

like image 148
Jitesh Mohite Avatar answered Jul 08 '26 16:07

Jitesh Mohite


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);
}
like image 27
ego Avatar answered Jul 08 '26 15:07

ego