Flutter: filter list as per some condition
Asked Answered
M

4

196

I'm having a list of movies. That contains all animated and non-animated movies. To identify whether it's Animated or not there is one flag called isAnimated.

I want to show only Animated movies. How can I do that?

Mild answered 30/3, 2018 at 17:12 Comment(0)
E
391

toList() is missing to materializer the result

_AnimatedMovies = AllMovies.where((i) => i.isAnimated).toList();
Eppes answered 30/3, 2018 at 17:14 Comment(5)
No work here :( . It says type 'Where Iterable<>' is not a subtype of type 'ListAgainst
If you need a List add .toList()Kalagher
It worked like charm actually I was creating an app in which I have some static data (list of a model) and when I am navigating to a single view page I am sending the id of the model and I am finding the model by id and showing it's data in the single view page. I am doing like this CompanyModel company = companies.where((c) => c.id == companyId).toList().first;Hunsinger
What would be the null safe version of this?Royer
@JoelGMathew I think AllMovies.whereNotNull().where((i) => i.isAnimated).toList(); (not tested)Kalagher
S
28

The Solution is here

Just try with this Function getCategoryList(),
Here the condition will be catogory_id == '1' from the list

List<dynamic> getCategoryList(List<dynamic> inputlist) {
    List outputList = inputlist.where((o) => o['category_id'] == '1').toList();
    return outputList;
  }
Spread answered 27/5, 2021 at 12:24 Comment(0)
R
9

You can use this for specific condition

List<String> strings = ['one', 'two', 'three', 'four', 'five'];
List<String> filteredStrings  = strings.where((item) {
   return item.length == 3;
});
Ravelment answered 4/4, 2021 at 3:46 Comment(0)
L
4

where function on a List returns Iterable, you have to convert it to List using the function List.from(Iterable).

So in the above scenario, you should use the following code snippet.

Iterable _AnimatedMoviesIterable = AllMovies.where((i) => i.isAnimated);

_AnimatedMovies = List.from(_AnimatedMoviesIterable);

Edited:

As per Günter Zöchbauer solution, we can use a single line instead of multiple. So the code is

_AnimatedMovies = AllMovies.where((i) => i.isAnimated).toList();
Lynnette answered 29/12, 2019 at 11:59 Comment(2)
Iterables have a toList() method which is much easier to read IMHO.Kalagher
Agreed @GünterZöchbauer. We can use AllMovies.where((i) => i.isAnimated).toList(); as you mentionedLynnette

© 2022 - 2024 — McMap. All rights reserved.