【问题标题】:dart/flutter - Class 'Datum' has no instance method '[]'飞镖/颤振 - 类“基准”没有实例方法“[]”
【发布时间】:2021-07-10 20:57:43
【问题描述】:

我有一个从 API 获取数据的 Podo 类。 那工作正常。在下拉字段中,我使用 id 的值并显示名称。

来自 api 响应的示例 Json 数据如下所示:

{"jsonapi":{"version":"1.0"},"data":[{"type":"testkit","id":"1","attributes":{"active":true,"testType":"type1","code":"T101","name":"TestName1","infos":{},}},{"type":"testkit","id":"2","attributes":{"active":true,"testType":"type2","code":"T102","name":"TestName2","productId":null,"infos":{}}}]}

快照:

child: FutureBuilder(
       future: _testkit,
       builder: (context,
       AsyncSnapshot<TestkitList> snapshot) {

drowdownFieldWidget 代码如下:

DropdownButtonFormField<String>(
hint:Text("Select Testkit Name"),
value: _selectedTestkit,
                onChanged: (newValue) {
                    setState(() {
                    _selectedTestkit = newValue;
_selectedTestType = getTestType()// this I am trying to get the value of test type, but not working.

                    });
                },
                validator: (value) => value ==
                        null
                    ? 'Please select the Testkit'
                    : null,
                items: (snapshot.data.data)
                    .map((item) =>
                        DropdownMenuItem<
                            String>(
                            child: Text(
                            item.attributes.name
                                        .length >
                                    30
                                ? item
                                    .attributes
                                    .name
                                    .substring(
                                        0, 30)
                                : item
                                    .attributes
                                    .name,
                            ),
                            value: item.id,
                        ))
                    .toList(),
                );
            }
        }
        }),
)),

现在除了选中项的id,我还需要访问attributestestType的值

我尝试通过创建函数getTestType() 来访问该值,如下所示:

getTestType() async {    

    final List testkits = await responsetestkit.then((value) => value.data);
    print("below line is printed in function getTestType");
    print(testkits.runtimeType);
    
    print(testkits);
    var testtype =
        testkits.firstWhere((testkit) => testkit["id"] == _selectedTestkit);  

    print(testtype);
    
  }

此函数返回错误 - Class 'Datum' has no instance method '[]'.

如果需要任何进一步的信息,请告诉我。

更新:Podo 文件内容:

import 'dart:convert';

TestkitList testkitListFromMap(String str) => TestkitList.fromMap(json.decode(str));

String testkitListToMap(TestkitList data) => json.encode(data.toMap());

class TestkitList {
    TestkitList({
        this.jsonapi,
        this.data,
    });

    Jsonapi jsonapi;
    List<Datum> data;

    factory TestkitList.fromMap(Map<String, dynamic> json) => TestkitList(
        jsonapi: json["jsonapi"] == null ? null : Jsonapi.fromMap(json["jsonapi"]),
        data: json["data"] == null ? null : List<Datum>.from(json["data"].map((x) => Datum.fromMap(x))),
    );

    Map<String, dynamic> toMap() => {
        "jsonapi": jsonapi == null ? null : jsonapi.toMap(),
        "data": data == null ? null : List<dynamic>.from(data.map((x) => x.toMap())),
    };
}

class Datum {
    Datum({
        this.type,
        this.id,
        this.attributes,
    });

    String type;
    String id;
    Attributes attributes;

    factory Datum.fromMap(Map<String, dynamic> json) => Datum(
        type: json["type"] == null ? null : json["type"],
        id: json["id"] == null ? null : json["id"],
        attributes: json["attributes"] == null ? null : Attributes.fromMap(json["attributes"]),
    );

    Map<String, dynamic> toMap() => {
        "type": type == null ? null : type,
        "id": id == null ? null : id,
        "attributes": attributes == null ? null : attributes.toMap(),
    };
}

class Attributes {
    Attributes({
        this.active,
        this.testType,
        this.code,
        this.name,        
        this.infos,
        
    });

    bool active;
    String testType;

【问题讨论】:

  • 你能打印testkits值吗?
  • 是的。我可以打印 testkit 值 id,也可以在下拉列表中显示 testkit 名称。

标签: flutter dart


【解决方案1】:

首先,你getTestType方法被标记为async,那么这只会返回一个Future并且需要then或者await来获取值:

onChanged: (newValue) async {
  _selectedTestkit = newValue; 
  _selectedTestType = await getTestType();
  setState(() {});
},

其次,getTestType 方法不返回任何值。修复添加返回值:

getTestType() async {    
  final List testkits = await responsetestkit.then((value) => value.data);
  print("below line is printed in function getTestType");
  print(testkits.runtimeType);
  
  print(testkits);
  var testtype =
      testkits.firstWhere((testkit) => testkit["id"] == _selectedTestkit);  

  print(testtype);
  return testtype;
}

【讨论】:

  • 我仍然遇到同样的错误。完整的错误是这样的:Exception has occurred. NoSuchMethodError (NoSuchMethodError: Class 'Datum' has no instance method '[]'. Receiver: Instance of 'Datum' Tried calling: []("id"))
  • 您的项目中有一个名为Datum 的类?
  • 测试套件有一个基准实例列表?如果是,您可以在帖子中添加此类的定义吗?
  • 是的,pod 文件 testkitlist 包含 Testkitlist 类和 datum 类。
  • 我认为您是 dart/flutter 大师。有效。实际上,出于我的目的,我需要testtype.attributes.testtype 也可以。非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-02-27
  • 2020-09-20
  • 1970-01-01
  • 2022-06-20
  • 2020-12-25
  • 2020-11-05
  • 1970-01-01
相关资源
最近更新 更多