Flutter报错NoSuchMethodError:null调用data getter问题求助
问题描述
尝试关联文章页面与搜索页面内容时,出现以下错误:
构建Builder(dirty)时抛出NoSuchMethodError:
在null对象上调用了getter 'data'。
接收者:null
尝试调用:data
相关代码如下:
class _SearchPageState extends State<SearchPage> { List<Article> _searchedPost = []; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: TextField( style: const TextStyle(color: Colors.white), decoration: const InputDecoration( hintText: 'Search Post', hintStyle: TextStyle(color: Colors.white), border: InputBorder.none), onChanged: (val) { setState(() { _searchedPost = widget.posts.where((el) => el.title.contains(val)).toList(); }); }, ), ), /// Body body: _searchedPost.isEmpty ? Center( child: Text( 'Nessun articolo disponibile', textAlign: TextAlign.center, style: Theme.of(context).textTheme.headline6, ), ) : ListView.builder( itemCount: _searchedPost.length, itemBuilder: (context, i) { return Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ Card( margin: const EdgeInsets.all(10), elevation: 5, shadowColor: Colors.black26, color: Colors.white, child: InkWell( child: ClipRRect( borderRadius: BorderRadius.circular(10), child: Column( mainAxisSize: MainAxisSize.min, children: [ _searchedPost[i].urlImage == null ? const Text("Nessuna immagine caricata") : Image.network( _searchedPost[i].urlImage, width: double.infinity, height: 220, fit: BoxFit.cover, ), // Title article Column( children: [ Padding( padding: const EdgeInsets.only( left: 16, top: 16, bottom: 16), child: Row( children: [ Expanded( child: Text( _searchedPost[i].title, maxLines: 3, overflow: TextOverflow.clip, softWrap: true, style: const TextStyle( fontSize: 18, fontWeight: FontWeight.w600, fontFamily: "Raleway", ), ), ), ], ), ) ], ), ], ), ), onTap: () { Navigator.push( context, MaterialPageRoute( builder: (context) => ArticlePage( data: snapshot.data?[i], ), ), ); }, ), ), ], ); }, ), ); } }
解决方案
错误根源是代码里的snapshot变量根本没在当前作用域定义,属于无中生有。现在搜索后的文章数据都存在_searchedPost列表里,跳转ArticlePage时应该传这个列表对应索引的元素。
修改onTap回调里的代码:
onTap: () { Navigator.push( context, MaterialPageRoute( builder: (context) => ArticlePage( data: _searchedPost[i], ), ), ); },
如果想更严谨,避免极端情况下列表元素为空的问题,可以加个空值判断:
onTap: () { final targetArticle = _searchedPost[i]; if (targetArticle != null) { Navigator.push( context, MaterialPageRoute( builder: (context) => ArticlePage(data: targetArticle), ), ); } },
内容的提问来源于stack exchange,提问作者Pimpi Rimpà
相关产品推荐
相关产品推荐

