首页 > 解决方案 > 飞镖/颤振 - 类“基准”没有实例方法“[]”

问题描述

我有一个从 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 之外,我还需要访问testTypeunderattributes

我尝试通过创建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;

标签: flutterdart

解决方案


首先,您getTestType的方法被标记为async,那么这只返回一个Future并且需要thenorawait来获取值:

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

推荐阅读