[ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: Bad state: No element

在调用List.first 时报出该异常

看一下List 中get first方法的源码:

 /**
   * Returns the first element.
   *
   * Throws a [StateError] if `this` is empty.
   * Otherwise returns the first element in the iteration order,
   * equivalent to `this.elementAt(0)`.
   */
  E get first {
    Iterator it = iterator;
    if (!it.moveNext()) {
      throw IterableElementError.noElement();
    }
    return it.current;
  }

通过源码可以看到在集合为空的时候会抛出一个异常, No element,

所以在调用List.first时,需要先判断list是否为空

你可能感兴趣的:(Flutter)