Flutter新手开发APP搜索功能空对象调用length报错求解决
问题原因与解决方案
The getter 'length' was called on null报错的核心原因是你声明的_foundedPlaces列表没有初始化默认值,初始状态为null,页面首次构建时直接调用_foundedPlaces.length触发空指针异常,同时你写的三目判断逻辑完全错误。
修复步骤
第一步:给列表设置初始空值,避免初始为null
把状态类里的声明代码:List<NewCategoryModel> _foundedPlaces;改为:
List<NewCategoryModel> _foundedPlaces = [];第二步:修正三目判断逻辑,原来的判断写反了,且判断条件不成立(列表的length属性是int类型,永远不可能等于null),同时要处理嵌套ListView的布局冲突
你原来的列表渲染部分代码:child: _foundedPlaces.length == null ? ListView.builder(...) : Center(child: Text("No places found"))改为:
child: _foundedPlaces.isNotEmpty ? ListView.builder( shrinkWrap: true, // 嵌套ListView必须加,适配父容器高度 physics: const NeverScrollableScrollPhysics(), // 禁用内部列表滚动,避免滚动冲突 itemCount: _foundedPlaces.length, itemBuilder: (context, index) { // 原来的item逻辑不变 return Slidable( actionPane: SlidableDrawerActionPane(), actionExtentRatio: 0.25, child: placeComponent(places: _foundedPlaces[index]), actions: <Widget>[ IconSlideAction( caption: 'Archive', color: Colors.transparent, icon: Icons.archive, onTap: () => print("archive"), ), IconSlideAction( caption: 'Share', color: Colors.transparent, icon: Icons.share, onTap: () => print('Share'), ), ], secondaryActions: <Widget>[ IconSlideAction( caption: 'More', color: Colors.transparent, icon: Icons.more_horiz, onTap: () => print('More'), ), IconSlideAction( caption: 'Delete', color: Colors.transparent, icon: Icons.delete, onTap: () => print('Delete'), ), ], ); }) : const Center(child: Text("No places found", style: TextStyle(color: Colors.black))),可选优化:如果你的
placesList方法可能返回null,可以在赋值时做空兼容处理,避免后续列表又被赋值为null:onSearch(String search) { setState(() { _foundedPlaces = placesList(search) ?? []; }); }
内容的提问来源于stack exchange,提问作者NabsDev
相关产品推荐
相关产品推荐

