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


75

我有电影列表。包含所有动画和非动画电影。要确定其Animated是否存在一个称为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"
        ),
      ),
    );
  }
}

WhereIterable <Object>不是List <Object>类型的子类型

Answers:



1

List上的function返回Iterable。您必须使用功能List.from(Iterable)将其转换为List。

因此,在上述情况下,您应该使用以下代码段。

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

_AnimatedMovies = List.from(_AnimatedMoviesIterable);


2
可迭代具有一种toList()更容易阅读恕我直言的方法。
君特Zöchbauer

1

您可以使用toList()方法获取所需的输出,如下所示

toList()收集此流中的所有元素List

解决以上问题:

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

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

代替

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

在此处输入图片说明

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.