Flutter:无法解决-类型'List <dynamic>'不是类型'List <Files>'的子类型

时间:2020-08-21 14:17:07

标签: flutter

我有一个模特

class Files {
  String fileName;
  bool type;

  Files(this.fileName, this.type);

  @override
  String toString() {
    return '{ ${this.fileName}, ${this.type} }';
  }
}

接下来,我定义列表paths = [];

然后我在此行中添加文件名和布尔类型,以查明该文件是否为目录

    for (final file in files) {
      print(file.path);
    paths.add(Files(file.name.toString(), file.isDirectory));
    }
    return paths.toList();

我得到以下数据: enter image description here

当我开始使用以下代码构建ListView时:

  Widget listViewWidget(List<Files> file) {
    return Container(
      child: ListView.builder(
          scrollDirection: Axis.vertical,
          shrinkWrap: true,
          itemCount: file.length,
          itemBuilder: (context, position) {
            return Card(
              elevation: 8.0,
              margin: new EdgeInsets.symmetric(horizontal: 10.0, vertical: 6.0),
              child: Container(
                decoration: BoxDecoration(color: Color.fromRGBO(133, 123, 122, .9)),
                child: ListTile(
                  onTap: () {},
                  contentPadding: EdgeInsets.symmetric(horizontal: 20.0, vertical: 10.0),
                  title: Text(
                    file[position].type ? file[position].fileName+" This is a Folder" : file[position].fileName+" This is a file",
                    style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold),
                  ),
                ),
              ),
            );
          }
      ),
    );
  }

我收到以下错误: type 'List<dynamic>' is not a subtype of type 'List<Files>'

任何人都可以提出问题所在吗?

2 个答案:

答案 0 :(得分:1)

如果将函数参数的类型注释为List<Files>,则必须正确地传递它。您没有显示对listViewWidget()的呼叫,所以我不确定在哪里,但是您缺少类型注释。

如果您要进行listViewWidget(paths),则声明var paths = <Files>[];应该可以解决问题。

答案 1 :(得分:1)

List上,您不能插入2个值。您只能插入一个File对象。 此外,您不能假定动态列表的类型为类。 dynamic应该是“基本”类型,例如intStringdoublebool,因为假设整个对象类型可能很危险。

我的建议是:

List<File> paths = List<File>();

这样,您可以执行以下操作:

paths.add(fileObject);

请记住,fileObject必须是File类的对象。