【问题标题】:Flutter: Call a method from a class based on propertiesFlutter:根据属性从类中调用方法
【发布时间】:2021-12-11 22:21:05
【问题描述】:

目标是使用父类的属性来调用方法并扩展该类的内容。

以下代码旨在根据其父类的属性调用方法。它返回一个类型错误。

它是这样称呼的:

MyToolbar(data: [
  {
    'MySecondClass': ['red','green','purple']
  }
])

这是类:

    class MyToolbar extends StatelessWidget {
      MyToolbar({required this.data})
      final List data;

      ToolbarContent(type, data) {
        if (type == 'MySecondClass') {
          return MySecondClass(toggles: data);
      }

      @override
      Widget build(BuildContext context) {
        return Stack(children:[
          for (List childData in data)
          ToolbarContent('mySecondClass', childData),
    
    ])}

首先这会返回以下类型错误。

_TypeError (type '_InternalLinkedHashMap<String, List<String>>' is not a subtype of type 'List<dynamic>')

其次,列表需要找到属性数据的键,以便为函数“ToolbarContent”设置正确的函数名。

【问题讨论】:

    标签: flutter class methods properties


    【解决方案1】:

    默认情况下,Dart 将任何 List 设置为 List&lt;dynamic&gt;。这就是错误所说的。你需要投射你的名单,试试这个final List&lt;Map&lt;String, List&lt;String&gt;&gt; data;

    【讨论】:

      【解决方案2】:

      这里有一些问题。首先,如 temp_ 所述,您需要将 List 类型设置为 data,在本例中为 List&lt;Map&lt;String,List&lt;String&gt;&gt;

      其次是for (List childData in data)实际上需要是for (Map&lt;String,List&lt;String&gt;&gt; childData in data)

      第三个是假设,但我认为您的for 循环中有一个错字,其中mySecondClass 应该是MySecondClass(或其他方式)

      正确的代码如下:

      class MyToolbar extends StatelessWidget {
        final List<Map<String, List<String>>> data;
      
        MyToolbar({required this.data});
      
        @override
        Widget build(BuildContext context) {
          var children = <Widget>[];
          data.forEach((childData) {
            childData.forEach((key, stringList) {
              //I'm assuming Toolbar content takes the key of the map i.e. MySecondClass
              //as the first param and the List for the key as the second param
              children.add(ToolbarContent(key, stringList));
            });
          });
          return Stack(
            children: children,
          );
        }
      }
      

      注意:我还假设 ToolbarContent 是另一个类,但如果不是,请告诉我。

      【讨论】:

      • 太棒了。非常感谢。
      猜你喜欢
      • 2014-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-31
      • 2018-05-12
      • 1970-01-01
      相关资源
      最近更新 更多