flutterflutter-dropdownbutton

Get user details from a dropdown list


I have a dropdown list populated with users, I want to get the user id and pass to a function whenever a user is selected from the list

An unhandled exception is occurring instead

the exception

E/flutter (28482): [ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: Null check operator used on a null value

The below snippet is where how I am fetching the users

User? sid;
  List<User> users = [];

  //fetch users
  Future<List<User>>? getUsers() async {
    var result = await client.get(usersUrl);
    return userFromJson(result.body);
  }

  Future<void> fetchandShow() async {
    final users = await getUsers();
    setState(() {
      this.users = users ?? [];
    });
  }

  @override
  void initState() {
    super.initState();
    fetchandShow();
  }

below is the dropdownbutton where I am displaying the users

DropdownButtonFormField<User>(
                    hint: Text('Select user'),
                    decoration: InputDecoration(
                      border: InputBorder.none,
                    ),
                    value: sid,
                    items: users
                        .map((item) => DropdownMenuItem(
                              value: item,
                              child: Text(
                                item.username,
                                style: TextStyle(fontSize: 20.0),
                              ),
                            ))
                        .toList(),
                    onChanged: (item) => setState(() {
                      sid!.id = item as String?;
                      print(sid!.id);
                    }),
                  ),

below is where i want to pass the user id

ElevatedButton(
                onPressed: () async {
                  await createNote(
                      _bodyController.text, int.parse(sid!.id.toString()));
                  Navigator.pop(context);
                },
                child: Text('submit'),
              )

Solution

  • Your item is of User type, Handle onChanged as below:

           onChanged: (item) => setState(() {
                      sid = item;
                     
                    }),