Flutter开发中VS Code提示snapshot.data.length报错的原因咨询
问题描述
环境配置
- Visual Studio Code 版本:1.52.0
- Node.js:12.14.1
我在Flutter代码里碰到一个奇怪的问题:明明已经通过if (snapshot.connectionState == ConnectionState.done && snapshot.hasData)判断异步请求完成且snapshot存在数据,但snapshot.data.length这一行还是报错。我认为这是编辑器的问题,而非Flutter语言本身的问题。
原代码片段
body: FutureBuilder<List<Post>>( future: postServiceData, builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.done && snapshot.hasData){ // 此处已做判断 return ListView.builder( itemCount: snapshot.data.length, // 此处因.length报错 itemBuilder: (context, index) { final post = snapshot.data![index]; return Padding( padding: const EdgeInsets.all(8.0), child: ListTile( title: Text(post.title.toUpperCase()), subtitle: Text(post.body), onTap: () { // 点击列表项时执行操作 }, ), ); }); } else { return Center(child: CircularProgressIndicator()); } }, ),
临时解决方法
目前我通过添加空断言运算符来临时解决这个问题:
itemCount: snapshot.data!.length,
内容的提问来源于stack exchange,提问作者Willian
相关产品推荐
相关产品推荐

