【发布时间】:2021-07-15 10:55:00
【问题描述】:
我正在使用 Provider 从 API 获取数据。所以现在我正在尝试根据路线 ID 过滤停靠点。我知道我应该使用where 方法,但它只给了我一个数组元素。我可以通过使用initState 并在其中使用过滤器来过滤虚拟数据,但是我正在尝试学习使用 Provider 包,我很好奇如何通过提供程序包过滤所有数据?
之前我是这样做的:List<Routes> routes = Provider.of<List<Routes>>(context).where((element) => element.ttId == widget.ttId).toList();
我直接根据 id 进行了过滤,但现在我为过滤的项目创建了另一个数组,我需要将它与提供程序一起使用,但我不明白如何。
我还想提一下,这个 id 是不相关的,即两个模型内部没有相同的 id,所以这就是我在这里问的原因。而且我正在使用未来的提供者来获取数据。
这是用户点击的第一个屏幕并转到另一个屏幕,其中包含过滤数据:
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => StopsPage(
stId: routes[index].mrId,
stTitle: routes[index].mrTitle,
)));
},
);
这是所有数据都应该显示和过滤的第二个屏幕:
class StopsPage extends StatelessWidget {
final String stTitle;
final int stId;
const StopsPage({Key key, @required this.stTitle, @required this.stId}) : super(key: key);
@override
Widget build(BuildContext context) {
//this line fetches the API
List<Stop> stop = Provider.of<List<Stop>>(context);
//this arrys for putting all items which was filtered by id
List <Stop> filteredStops = [];
//here I am trying to make a filtration
filteredStops.where((element) => element.stId == stId).toList();
return Scaffold(
appBar: AppBar(
actions: [
IconButton(icon: Icon(Icons.refresh_outlined), onPressed: (){})
],
),
body: stop == null
? Center(child: CircularProgressIndicator())
:
ListView.builder(
itemCount: filteredStops.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(filteredStops[index].stTitle),
【问题讨论】:
标签: flutter dart flutter-provider