当前位置:网站首页>Flutter | firstWhere 报错问题
Flutter | firstWhere 报错问题
2022-07-23 12:08:00 【无夜之星辰】
报错代码:
final array = [1, 2, 3];
final a = array.firstWhere((element) => element == 4);
print(a);
控制台显示:
Bad state: No element
我也是醉了,没那个元素就直接报错了,实在是太脆弱了。
千万不要忽略这个问题,报错则意味着后面的代码都不会执行了,肯定会出现bug。
会什么会报错?
官方文档写的是:
If no element satisfies test, the result of invoking the orElse function is returned. If orElse is omitted, it defaults to throwing a StateError.
如果没找到匹配元素,会执行 orElse 函数,如果没有 orElse 函数,会抛出 StateError。
解决方案1:
使用 try catch 捕获异常:
try {
final array = [1, 2, 3];
int? a = array.firstWhere((element) => element == 4);
print(a);
} catch (error) {
// 没有那个元素
// 做处理
}
解决方案2:
传入 orElse 回调,没有指定元素的时候直接返回 null:
final List<int?> array = [1, 2, 3];
int? a = array.firstWhere(
(element) => element == 4,
orElse: () => null,
);
print(a);
控制台打印 null。
边栏推荐
- 反转链表画图演示
- How to solve the problem of forgetting the Oracle password
- lc marathon 7.23
- [in simple terms] from self information to entropy, from relative entropy to cross entropy, nn Crossentropyloss, cross entropy loss function and softmax, multi label classification
- 现代商业无代码开发平台的治理和网络安全
- Jianzhi offer II 115. reconstruction sequence: topological sorting construction problem
- 24 道几乎必问的 JVM 面试题,我只会 7 道,你能答出几道?
- Packaging and use of fmdb
- TranslucentTB 推荐
- Esp8266 nodemcu flash file system (spiffs)
猜你喜欢

24 道几乎必问的 JVM 面试题,我只会 7 道,你能答出几道?

Bubble sort - just read one

After effects tutorial, how to create animation in after effects?

VRRP+MSTP配置详解【华为eNSP实验】

来自大佬洗礼!2022头条首发纯手打MySQL高级进阶笔记,吃透P7有望

再获殊荣 | OpenSCA获选中国软博会“全球十大开源软件产品”
![Vrrp+mstp configuration details [Huawei ENSP experiment]](/img/d3/0334a9c6d6ee8c309712e73ed8c05a.png)
Vrrp+mstp configuration details [Huawei ENSP experiment]

关于初始化page入参的设计思路

Basic concept and deployment of kubernetes

Leetcode high frequency question: the array can be changed into a non descending state after at least several operations
随机推荐
Google Earth engine -- null value problem in image statistics
js过滤/替换敏感字符
2022蓝帽杯初赛wp
Bean Validation核心組件篇----04
MySQL - six logs
死锁、饥饿、死循环之间的区别
Mathematical Modeling Typesetting
2022 blue hat cup preliminary WP
Pydensecrf installation
ESP8266 NodeMCU 闪存文件系统(SPIFFS)
来自大佬洗礼!2022头条首发纯手打MySQL高级进阶笔记,吃透P7有望
为什么使用opengaussjdbc的时候老是出现FATAL?(标签-数据库|关键词-user)
满足多种按键的高性价比、高抗干扰触摸IC:VK3606D、VK3610I、VK3618I 具有高电源电压抑制比
[2023 approved in advance] BOE
AC自动机和Fail树
redis 哨兵模式
将.calss文件转为.jar-idea篇
es6把多个class方法合并在一起
MySQL soul 16 ask, how many questions can you hold on to?
WSAStartup函数的用途