Home > Software engineering >  Flutter dropdown with future builder
Flutter dropdown with future builder

Time:01-25

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?

CodePudding user response:

You can use the below the line of sample code for dropdown widget

DropdownButton<String>(
          items: <String>['One', 'Two', 'Three', 'Four'].map((String value) {
            return DropdownMenuItem<String>(
              value: value,
              child: Text(value),
            );
          }).toList(),
          onChanged: (v) {},
        ),

enter image description here

CodePudding user response:

you can create it like this

 DropdownButton<int>(
          items: [
            DropdownMenuItem(
              child: Text("${roleModel.role}"),
              value: roleModel.id,
            ),
          ],
          onChanged: (value) {},
        ),
  • Related