此代码运行良好并在列表视图中显示数据:
return ListView.builder(
itemCount: snapshot.data.data.length,
itemBuilder: (context, index) {
print(snapshot.data.data[index]);
return ListTile(
title:
Text(snapshot.data.data[index].id.toString()),
subtitle: Text(
snapshot.data.data[index].attributes.name==null?'Not Set':snapshot.data.data[index].attributes.name,
),
);
});
但是当我在下拉小部件中使用相同的时,它会抛出错误:
return DropdownButton<String>(
hint: Text("Select"),
value: _selectedTestkit,
onChanged: (newValue) {
setState(() {
_selectedTestkit = newValue;
});
},
items: snapshot.data.data.map((item) =>
DropdownMenuItem<String>(
child: Text(item.id),
value:item.id,
)).toList(),
);
}
}
}),
),
这是我得到的错误:
There should be exactly one item with [DropdownButton]'s value: .
Either zero or 2 or more [DropdownMenuItem]s were detected with the same value
'package:flutter/src/material/dropdown.dart':
Failed assertion: line 855 pos 15: 'items == null || items.isEmpty || value == null ||
items.where((DropdownMenuItem<T> item) {
return item.value == value;
}).length == 1'
但在列表视图构建器中我得到了这个结果:
1 testname1
2 testname2
3 testname3
4 testname4
更新:
我曾经在下拉列表中添加自定义值,如下所示:
List data = json.decode(response.body);
data.add('other');
另一个将显示在下拉列表中。
但是当我尝试现在的未来方法时
Future<TestkitList> fetchTestkitId() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
Uri testkiturl = Uri.https(staging_url, "testkits");
final response = await http.get(testkiturl, headers: {
'Accept-Type': 'application/json',
"Content-Type": "application/json",
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
print(response.body);
print('this was printed before json decode');
var responsetestkit = Future.value(testkitListFromMap(response.body));
responsetestkit.add('other');//here I am trying to add a custom item for dropdown
setState(() {
_testkit = responsetestkit;
print(_testkit);
});
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
print(response.body);
throw Exception('Failed to load TESTKITLIST');
}
}
但在这里我收到错误 - The method 'add' isn't defined for the type 'Future'.
答案 0 :(得分:0)
改变这个
if (response.statusCode == 200) {
return Future.value(testkitListFromMap(response.body));
} else {
throw Exception('Failed to load TESTKITLIST');
}
为此:
if (response.statusCode == 200) {
return Future.value(testkitListFromMap(response.body["data"]));//you need to add "data" to access your items based on your data class.
} else {
throw Exception('Failed to load TESTKITLIST');
}