类型'List <dynamic>'不是'List <Widget>'类型的子类型

Ara*_*ash 35 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(),
        );
      },
    );
  }
Run Code Online (Sandbox Code Playgroud)

但是我得到了这个错误

type 'List<dynamic>' is not a subtype of type 'List<Widget>'
Run Code Online (Sandbox Code Playgroud)

这里出了什么问题?

Jon*_*ams 67

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

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

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

  • 嗯,解决了这个问题。但这有点奇怪,我是飞镖新手,所以我不能说我真的理解它。 (3认同)
  • 可能与使用 Dart 2 的强模式或颤振有关。 (2认同)
  • 你能解释一下为什么“new ListTile”中的“new”是必要的吗? (2认同)

Rah*_*ran 63

我在 firestore 中有一个字符串列表,我试图在我的应用程序中读取它。当我尝试将其转换为字符串列表时,我遇到了同样的错误。

type 'List<dynamic>' is not a subtype of type 'List<Widget>'
Run Code Online (Sandbox Code Playgroud)

这个解决方案帮助了我。一探究竟。

type 'List<dynamic>' is not a subtype of type 'List<Widget>'
Run Code Online (Sandbox Code Playgroud)


小智 22

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

List<'YourModel'>.from(_list.where((i) => i.flag == true));
Run Code Online (Sandbox Code Playgroud)


Abd*_*pal 13

我已经通过转换Map为解决了我的问题Widget

      children: snapshot.map<Widget>((data) => 
               _buildListItem(context, data)).toList(),
Run Code Online (Sandbox Code Playgroud)

  • 为什么它对我不起作用?飞镖零安全 (2认同)

小智 8

我的解决方案是,您可以投射List<dynamic>into ,您可以在intoList<Widget>之后添加一个简单的代码,就像我将在下面向您展示的代码snapshot.data.documents.mapsnapshot.data.documents.map<Widget>

由此

return new ListView(
          children: snapshot.data.documents.map((document) {
            return new ListTile(
              title: new Text(document['name']),
              subtitle: new Text("Class"),
            );
          }).toList(),
        );
Run Code Online (Sandbox Code Playgroud)

进入这个

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


小智 7

我认为您在某些小部件的子属性中使用 _buildBody ,因此孩子们需要一个List Widget(小部件数组)并且 _buildBody 返回一个'Listdynamic'

以一种非常简单的方式,您可以使用变量来返回它:

// 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
)
Run Code Online (Sandbox Code Playgroud)

示例(flutter create test1cd test1编辑 lib/main.dartflutter run):

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

}
Run Code Online (Sandbox Code Playgroud)

另一个在小部件列表(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'.");},
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

我做了一个完整的例子,我使用动态小部件在屏幕上显示和隐藏小部件,您也可以看到它在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());
  }
}
Run Code Online (Sandbox Code Playgroud)

也许它对某人有帮助。如果它对您有用,请让我知道,请单击向上箭头。谢谢。

https://dartpad.dev/b37b08cc25e0ccdba680090e9ef4b3c1