颤动: 根据某些条件过滤器列表

我有一个电影清单。包含所有动画和非动画电影。为了确定它是否是动画的,有一个标志称为 是动画

我只想放动画片。我写的代码过滤出只有动画电影,但得到一些错误。

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"
),
),
);
}
}

WhereIterable is not subtype of type List

204638 次浏览

缺少 toList()来实现结果

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

如果 List 上的函数返回 Iterable,则必须使用函数 List.from (Iterable)将其转换为 List。

因此,在上面的场景中,您应该使用下面的代码片段。

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


_AnimatedMovies = List.from(_AnimatedMoviesIterable);

编辑:

根据 Günter Zöchbauer 的解决方案,我们可以用一行代替多行

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

您可以在特定的情况下使用它

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

解决方案就在这里

只要尝试使用这个函数 getCategory oryList () ,
这里的条件是列表中的 catory _ id = =’1’

List<dynamic> getCategoryList(List<dynamic> inputlist) {
List outputList = inputlist.where((o) => o['category_id'] == '1').toList();
return outputList;
}