This is my data model
class RoleModel {
int? id;
String? role;
RoleModel({this.id, this.role});
RoleModel.fromJson(Map<String, dynamic> json) {
id = json['id'];
role = json['role'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['id'] = id;
data['role'] = role;
return data;
}
}
This is my code to get api data
List<RoleModel> roles = [];
Future<List<RoleModel>> getRoles() async {
try {
final response = await http
.get(Uri.parse('https://localhost:8000/roles'));
var data = jsonDecode(response.body.toString());
if (response.statusCode == 200) {
for (Map<String, dynamic> i in data) {
roles.add(RoleModel.fromJson(i));
}
return roles;
} else {
throw Exception('Failed to load roles:$response');
}
} catch (e) {
throw Exception('Failed due to: $e');
}
}
How can I create a dropdown button which will have ‘id’ as value and ‘role’ will be displayed as text?
3
Answers
you can create it like this
You can use the below the line of sample code for dropdown widget
You can also create a dropdown button just using a custom package from pub.dev :
[1]: https://pub.dev/packages/dropdown_button2/install
I’ve received an error, because the http URL isn’t accessible now. If you try it with a new URL, i think this code will work correctly.