I am working on e commerce application in that app I want to set dropdown data from api. I am fresher in flutter so I need to help
Dropdown Code
DropdownButton<String>(
value: _selectedOption,
items:_options.map<DropdownMenuItem<String>>(
(String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
onChanged: (value) {
setState(() {
_selectedOption = value!;
});
},
),
@override
void initState() {
ProductDetailsNet.fetchProductDetails(widget.utils.id.toString()).then(
(value) {
List<String> fetchedOptions = value.cast<String>();
List<String> options = [];
for (String option in fetchedOptions) {
String concatenatedOption = option;
options.add(concatenatedOption); }
setState(() {
_options = options;
_selectedOption = _options.isNotEmpty ? _options[0] : '';
});
}
);
}
my api calling code:
class ProductDetailsNet{
static List<ProductDetailsUtils> parseService (String responseBody){
var list=json.decode(responseBody) as List<dynamic>;
List<ProductDetailsUtils> serviceList=list.map((e) => ProductDetailsUtils.fromJson(e)).toList();
return serviceList;
}
static Future<List<ProductDetailsUtils>> fetchProductDetails(String pid ) async{
final url=Uri.parse('https://wiz-mart.com/api/prodetails.php');
SharedPreferences prefs = await SharedPreferences.getInstance();
String? username=prefs.getString("username");
final queryParams = {
'username': username,
'pid': pid,
};
final newUrl = url.replace(queryParameters: queryParams);
print(newUrl);
try{
final response = await http.get(newUrl);
if (response.statusCode == 200)
{
final data = json.decode(response.body);
List<String> options = [];
String option1 = "${data['psize']} ${data['uom']}";
String option2 = "${data['psize2']} ${data['uom2']}";
String option3 = "${data['price3']} ${data['uom3']}";
options.add(option1);
options.add(option2);
options.add(option3);
print('Login successful!');
print(response.body);
return parseService(response.body);
}else {
print('Login failed! Status code: ${response.statusCode}');
print('Response body: ${response.body}');
}
}catch (error) {
print('Error occurred: $error');
}
throw Exception('Unable to retrieve product details.');
}
when I run this code I got error Error occurred: type ‘String’ is not a subtype of type ‘int’ of ‘index’
and my data not set to the widgets. So what should I do for.
2
Answers
I’ve added the whole code from my own project. Think, test, and try to customize yourself.
API services
Here is how I called and implement API response in the dropdown.
Use Future Builder, It will take the stream and display data in your dropdown.
Here is the link of GitHub repo where i have used Future Builder
https://github.com/zeeshan564/News-Application/blob/API-Integration/lib/screens/home_screen/home_screen.dart