【发布时间】: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,我还需要访问attributes下testType的值
我尝试通过创建函数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 名称。