skip to Main Content

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


  1. you can create it like this

     DropdownButton<int>(
              items: [
                DropdownMenuItem(
                  child: Text("${roleModel.role}"),
                  value: roleModel.id,
                ),
              ],
              onChanged: (value) {},
            ),
    
    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
  3. You can also create a dropdown button just using a custom package from pub.dev :

    1. Add the latest version of dropdown_button2 to your pubspec.yaml file from
      [1]: https://pub.dev/packages/dropdown_button2/install
    2. Run ‘flutter pub add dropdown_button2’ this command from your terminal.
    3. Add ‘import ‘package:dropdown_button2/dropdown_button2.dart’; this line to your code page.
        import 'dart:convert';
        import 'package:dropdown_button2/custom_dropdown_button2.dart';
        import 'package:flutter/material.dart';
        import 'package:http/http.dart' as http;
    
        void main() => runApp(MyFlutterApp());
        
        class MyFlutterApp extends StatelessWidget {
          const MyFlutterApp({super.key});
        
          @override
          Widget build(BuildContext context) {
            return MaterialApp(
              debugShowCheckedModeBanner: false,
              home: HomePage(),
            );
          }
        }
        
        class HomePage extends StatefulWidget {
          const HomePage({super.key});
        
          @override
          State<HomePage> createState() => _HomePageState();
        }
        
        class _HomePageState extends State<HomePage> {
          @override
          
        
          List<String> get getAllRoles {
            List<String> allRoles = [];
            for (int i = 0; i < roles.length; i++) {
              allRoles.add('${roles[i].id}    ${roles[i].role}');
            }
            return allRoles; // String format of json taken from the web.
          }
        
          int index = 0;
          Widget build(BuildContext context) {
            return Scaffold(
              appBar: AppBar(
                title: const Text('Dropdown with id and role'),
              ),
              body: Padding(
                padding: const EdgeInsets.all(8.0),
                child: CustomDropdownButton2(
                  hint: 'Select Item',
                  dropdownItems: getAllRoles,
                  value: getAllRoles[index],
                  buttonWidth: double.infinity,
                  dropdownWidth: double.infinity,
                  buttonElevation: 7,
                  onChanged: (value) {
                    setState(() {
                      index = getAllRoles.indexOf(value.toString());
                    });
                  },
                ),
              ),
            );
          }
        }
        
        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;
          }
        }
        
        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');
          }
        }
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search