user16357470
user16357470

Reputation:

How to filter by ids using provider package Flutter/Dart?

I am using Provider to fetch data from the API. So now I am trying to filter stops based on routes id. I understood that I should use where method, but it gives me only one element of array. I can filtered dummy data by using initState and using filter inside this, but I am trying to learn to use Provider package and I am curious how can I filter all data through the provider package?

Previously I did this: List<Routes> routes = Provider.of<List<Routes>>(context).where((element) => element.ttId == widget.ttId).toList();

I did filtration based on id directly, but now I creted another array for filtered items and I need to use it with provider but I don't understand how.

Also I want to mention that this ids are unrelated i.e both models don't have the same ids inside them so that's why I am asking here. And also I am using future provider to fetch the data.

It is the first screen where user taps and go to the another screen with filtered data:

  onTap: () {
                      Navigator.push(
                          context,
                          MaterialPageRoute(
                              builder: (context) => StopsPage(
                                stId: routes[index].mrId,
                                stTitle: routes[index].mrTitle,
                                  )));
                    },
                  );

It is the second screen where all data should apper and be filtered:

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),

Upvotes: 0

Views: 1308

Answers (1)

kounex
kounex

Reputation: 1715

The where() function returns the list of objects which satisfy your predicate (in this case where the ids are the same) but you have to do that on a list which actually has data, you just mixed it up:

filteredStops = stop.where((element) => element.stId == stId).toList();

Upvotes: 1

Related Questions