我有 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),
);
}));
}
}
附带问题: 另外我在想是否有任何方法可以按标题过滤两个列表?
答案 0 :(得分:0)
错误是不言自明的,您在空对象上调用函数 where
,这是不允许的。
stops 可以为 Null 吗?
试试:
List<Stop> = stops?.where((element) => element.stId == stId).toList() ?? [];
或
List<Stop> filtered = [];
if (stops != null) {
filtered = stops.where((element) => element.stId == stId).toList();
}