输入&#39;列出<dynamic>&#39;不是类型&#39; List <widget>&#39;的子类型。

时间:2018-04-01 22:00:38

标签: dart flutter

我有一段代码,我是从Firestore示例中复制的:

Widget _buildBody(BuildContext context) {
    return new StreamBuilder(
      stream: _getEventStream(),
      builder: (context, snapshot) {
        if (!snapshot.hasData) return new Text('Loading...');
        return new ListView(
          children: snapshot.data.documents.map((document) {
            return new ListTile(
              title: new Text(document['name']),
              subtitle: new Text("Class"),
            );
          }).toList(),
        );
      },
    );
  }

但是我收到了这个错误

type 'List<dynamic>' is not a subtype of type 'List<Widget>'

这里出了什么问题?

7 个答案:

答案 0 :(得分:42)

这里的问题是类型推断以意想不到的方式失败。解决方案是为map方法提供类型参数。

snapshot.data.documents.map<Widget>((document) {
  return new ListTile(
    title: new Text(document['name']),
    subtitle: new Text("Class"),
  );
}).toList()

更复杂的答案是,虽然children的类型为List<Widget>,但该信息不会回流到map调用。这可能是因为map后跟toList,因为没有办法输入注释闭包的返回。

答案 1 :(得分:3)

我认为您在某些小部件的子级属性中使用了_buildBody,因此子级期望使用列表小部件(小部件数组)和_buildBody返回 “动态列表”

以非常简单的方式,您可以使用变量将其返回:

// you can build your List of Widget's like you need
List<Widget> widgets = [
  Text('Line 1'),
  Text('Line 2'),
  Text('Line 3'),
];

// you can use it like this
Column(
  children: widgets
)

示例( flutter创建test1 cd test1 编辑lib / main.dart flutter运行)) :

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  List<Widget> widgets = [
    Text('Line 1'),
    Text('Line 2'),
    Text('Line 3'),
  ];

  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text("List of Widgets Example")),
        body: Column(
          children: widgets
        )
      )
    );
  }

}

小部件列表(arrayOfWidgets)中使用小部件(oneWidget)的另一个示例。我将展示如何通过小部件(MyButton)来个性化小部件并减少代码的大小:

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  List<Widget> arrayOfWidgets = [
    Text('My Buttons'),
    MyButton('Button 1'),
    MyButton('Button 2'),
    MyButton('Button 3'),
  ];

  Widget oneWidget(List<Widget> _lw) { return Column(children: _lw); }

  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text("Widget with a List of Widget's Example")),
        body: oneWidget(arrayOfWidgets)
      )
    );
  }

}

class MyButton extends StatelessWidget {
  final String text;

  MyButton(this.text);

  @override
  Widget build(BuildContext context) {
    return FlatButton(
      color: Colors.red,
      child: Text(text),
      onPressed: (){print("Pressed button '$text'.");},
    );
  }
}

我做了一个完整的示例,我使用dynamic widgets在屏幕上显示和隐藏小部件,您也可以在dart fiddle上看到它在线运行。

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  List item = [
    {"title": "Button One", "color": 50},
    {"title": "Button Two", "color": 100},
    {"title": "Button Three", "color": 200},
    {"title": "No show", "color": 0, "hide": '1'},
  ];

  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text("Dynamic Widget - List<Widget>"),backgroundColor: Colors.blue),
        body: Column(
          children: <Widget>[
            Center(child: buttonBar()),
            Text('Click the buttons to hide it'),
          ]
        )
      )
    );
  }

  Widget buttonBar() {
    return Column(
      children: item.where((e) => e['hide'] != '1').map<Widget>((document) {
        return new FlatButton(
          child: new Text(document['title']),
          color: Color.fromARGB(document['color'], 0, 100, 0),
          onPressed: () {
            setState(() {
              print("click on ${document['title']} lets hide it");
              final tile = item.firstWhere((e) => e['title'] == document['title']);
              tile['hide'] = '1';
            });
          },
        );
      }
    ).toList());
  }
}

也许它可以帮助某人。如果对您有用,请告诉我单击向上箭头。谢谢。

https://dartpad.dev/b37b08cc25e0ccdba680090e9ef4b3c1

答案 2 :(得分:1)

这对我有用List<'YourModel'>.from(_list.where((i) => i.flag == true));

答案 3 :(得分:0)

我通过将地图转换为小部件来解决了我的问题

      children: snapshot.map<Widget>((data) => 
               _buildListItem(context, data)).toList(),

答案 4 :(得分:0)

您可以将动态列表转换为具有特定类型的列表:

logging_conf_path = os.path.join(os.path.dirname(__file__), 'logging.conf')
logging.config.fileConfig(logging_config_file_path)

答案 5 :(得分:0)

要将每个项目转换为小部件,请使用ListView.builder()构造函数。

通常,提供一个生成器功能,该功能可检查您要处理的物品类型,并返回适合该类型物品的小部件。

ListView.builder(
  // Let the ListView know how many items it needs to build.
  itemCount: items.length,
  // Provide a builder function. This is where the magic happens.
  // Convert each item into a widget based on the type of item it is.
  itemBuilder: (context, index) {
    final item = items[index];

    return ListTile(
      title: item.buildTitle(context),
      subtitle: item.buildSubtitle(context),
    );
  },
);

答案 6 :(得分:0)

通过添加 .toList() 更改为列表解决了问题