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'),
)
CodePudding user response:
Your item is of User type, Handle onChanged as below:
onChanged: (item) => setState(() {
sid = item;
}),
CodePudding user response:
Here "timeZoneType" is the List of data and once the user select any option from the dropdown, we will get the index ("accountIndex") of the item. Once we get the index of the item, we can just get that index item details by
"timeZoneType[index]"
var detailData = timeZoneType[index]
Column(
children: [
Container(
width: MediaQuery.of(context).size.width,
height: 45,
child: DropdownButtonHideUnderline(
child: Padding(
padding: const EdgeInsets.only(left: 20.0, right: 1),
child: DropdownButton(
hint: Text("Timezone", style: Constants.editTextStyleLight),
value: _currentSelectedValue.value,
items: timeZoneType
.map((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(
value,
style: Constants.editTextStyle,
),
);
}).toList(),
onChanged: (value) {
setState(() {
print(value);
accountIndex = timeZoneType.indexOf(value.toString());
print(accountIndex);
});
}),
),
),
),
],
)