方法 'where' 在 null 上调用。接收器:空 尝试调用:其中(闭包:(停止)=>布尔值)颤振/飞镖



我有2个屏幕,我想过滤,但我有这个错误:

The method 'where' was called on null.
Receiver: null
Tried calling: where(Closure: (Stop) => bool)

我创建了列表,用于放置所有过滤停止的值,并试图将其放入ListView,但我得到了这个错误。所以他们说我需要创建这些行来实现我的过滤目标:

List<Stop> filtered = [];
filtered = stops.where((element) => element.stId == stId).toList();

但是当我尝试这个时,我得到了一个错误。

这是两个屏幕:

class Stops extends StatelessWidget {
int stId;
int mrId;
String stTitle;
Stops({this.stId, this.stTitle, this.mrId,});
@override
Widget build(BuildContext context) {
List<Routes> routes = Provider.of<List<Routes>>(context).where((element) => element.mrId == mrId).toList();
return Scaffold(
appBar: AppBar(),
body: routes == null
? Center(
child: CircularProgressIndicator(),
)
: ListView.builder(
itemCount: routes.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(routes[index].mrTitle),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Stopin(
stId: routes[index].mrId,
)));
},
);
}));
}
}
class Stopin extends StatelessWidget {
final int stId;
const Stopin({Key key, this.stId}) : super(key: key);
@override
Widget build(BuildContext context) {
List<Stop> stops = Provider.of<List<Stop>>(context);
List<Stop> filtered = [];
filtered = stops.where((element) => element.stId == stId).toList();
return  Scaffold(
appBar: AppBar(),
body: stops == null
? Center(
child: CircularProgressIndicator(),
)
: ListView.builder(
itemCount: filtered.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(filtered[index].stTitle),
);
}));
}
}

一边问:此外,我在想,如果有任何方法来过滤这两个列表的标题?

这个错误是不言自明的,你在一个空对象上调用函数where,这是不允许的。

stop为空

试题:

List<Stop> = stops?.where((element) => element.stId == stId).toList() ?? [];

List<Stop> filtered = [];
if (stops != null) {
filtered = stops.where((element) => element.stId == stId).toList();
}

最新更新