I have a drop down button with a list of items in it that are fetched from the api, i need to send to the server the id of the selected item. So right when the user chooses the item and presses the Start Working button i need to send the chosen items id to the server, the problem that im having is working out with sending the chosen items id.
Future<void> postLocationId(String id) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
String? authorization = prefs.getString('authorization');
var url = 'some url';
try {
final response = await http.post(
Uri.parse(url),
headers: <String, String>{
'authorization': authorization ?? basicAuth.toString(),
"Content-Type": "application/json"
},
body: jsonEncode(id)
);
print(response.statusCode);
print(id);
} catch (er) {}
}
String? chooseLocation;
late Future<Response> futureData;
late Future<Response> futureDataForAccount;
bool _flag = true;
List<WorkingLocationData>? workingData;
List<AccountData>? accountData;
Scaffold(
body: FutureBuilder<List<Response>>(
future: Future.wait([futureData, futureDataForAccount]),
builder: (context, snapshot) {
if (snapshot.hasData) {
List<WorkingLocationData> data1 =
parsedData(snapshot.data![0].body);
workingData = data1;
AccountData data3 =
AccountData.fromJson(json.decode(snapshot.data![1].body));
child: DropdownButton<String>(
value: chooseLocation,
hint: const Text('Select a location'),
isExpanded: true,
items: workingData!.map((some) {
return DropdownMenuItem(
child: Text(some.name ' (${some.location})'),
value: some.id,
);
}).toList(),
onChanged: (String? displayedValue) {
setState(
() {
chooseLocation = displayedValue!;
},
);
},
),
),
SizedBox(height: height * 0.150),
Column(
children: [
ElevatedButton(
onPressed: () async {
final WorkingLocationData locatonData = workingData!.firstWhere((some) => some.location == chooseLocation);
await postLocationId(locatonData.id);
print(locatonData.id);
setState(() {
_flag = !_flag;
});
},
child: Text(_flag ? 'Start Work' : 'Stop Work'),
style: ElevatedButton.styleFrom(
primary: _flag ? Colors.teal : Colors.red,
),
),
],
CodePudding user response:
You need to add the parameter you want: postLocationId(String id).
Without changing the structure too much you can search through workingData for the item with the matching location and pass it on press like:
ElevatedButton(
onPressed: () async {
final WorkingLocationData locatonData = workingData!.firstWhere((some) => some.location == chooseLocation);
postLocationId(locatonData.id);
setState(() {
_flag = !_flag;
});
},
child: Text(_flag ? 'Start Work' : 'Stop Work'),
style: ElevatedButton.styleFrom(
primary: _flag ? Colors.teal : Colors.red,
),
),
If you're interested in a larger structural change I use https://pub.dev/packages/flutter_typeahead for this kind of thing
