Flutter:根据某些条件过滤列表

Flutter: Filter list as per some condition

我有一个电影列表。包含所有动画和非动画电影。要确定它是否是动画的,有一个名为 isAnimated.

的标志

我只想显示动画电影。我已经编写了代码来仅过滤掉动画电影,但出现了一些错误。

import 'package:flutter/material.dart';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(

        primarySwatch: Colors.blue,
      ),
      home: new HomePage(),
    );
  }
}

class Movie {
  Movie({this.movieName, this.isAnimated, this.rating});
  final String movieName;
  final bool isAnimated;
  final double rating;
}

List<Movie> AllMovies = [
  new Movie(movieName: "Toy Story",isAnimated: true,rating: 4.0),
  new Movie(movieName: "How to Train Your Dragon",isAnimated: true,rating: 4.0),
  new Movie(movieName: "Hate Story",isAnimated: false,rating: 1.0),
  new Movie(movieName: "Minions",isAnimated: true,rating: 4.0),
];



class HomePage extends StatefulWidget{
  @override
  _homePageState createState() => new _homePageState();
}


class _homePageState extends State<HomePage> {

  List<Movie> _AnimatedMovies = null;

  @override
  void initState() {
    super.initState();
    _AnimatedMovies = AllMovies.where((i) => i.isAnimated);
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      body: new Container(
        child: new Text(
            "All Animated Movies here"
        ),
      ),
    );
  }
}

toList() 缺少具体化结果

_AnimatedMovies = AllMovies.where((i) => i.isAnimated).toList();

列表上的 where 函数 returns 可迭代。您必须使用函数 List.from(Iterable).

将其转换为 List

所以在上面的场景中你应该使用下面的代码片段。

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

_AnimatedMovies = List.from(_AnimatedMoviesIterable);

您可以使用toList()方法来获得您想要的输出,如下所示

toList()List.

中收集此流的所有元素

解决上述问题:

添加一个toList()(此代码创建一个List<dynamic>

_AnimatedMovies = AllMovies.where((i) => i.isAnimated).toList();

而不是

_AnimatedMovies = AllMovies.where((i) => i.isAnimated);

where() 的输出是另一个 Iterable,您可以直接使用它来迭代它或应用其他 Iterable 方法。在下一个示例中,where() 的输出直接在 for-in 循环中使用。

var evenNumbers = AllMovies.where((i) => i.isAnimated).toList();
for (var i in evenNumbers) {
  print('$i');
}
  1. 您也可以使用 takeWhile

方法 takeWhile() 还可以帮助您从 Iterable 中过滤元素。

 _AnimatedMovies = AllMovies.takeWhile((i) => i.isAnimated).toList();

您可以将其用于特定条件

List<String> strings = ['one', 'two', 'three', 'four', 'five'];
List<String> filteredStrings  = strings.where((item) {
   return item.length == 3;
});

这里课程是一个列表。注释星号设置到课程列表的元素。 starred为bool型变量

courses = courses.where((element) => !element.starred).toList();

解决方法在这里

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;
  }