Loading Data from REST API into Dropdown in Flutter

Axiftaj
3 min readFeb 1, 2024

Loading data from a REST API into a dropdown menu is a common task in Flutter app development, especially when you need dynamic data selection. This process involves fetching data from a remote server, parsing it, and populating a dropdown widget with the retrieved data. Additionally, it’s essential to handle exceptions gracefully to provide a smooth user experience.

In this guide, we’ll walk through the steps to load data from a REST API into a dropdown menu in a Flutter application while also handling exceptions.

Source Code:

Step 1: Add Dependencies

First create Flutter project and add http package into yaml file

dependencies:
flutter:
sdk: flutter
http: ^0.13.3

Step 2: Posts Model

Let’s create posts model class, we will parse data using this model.

class PostsModel {
int? userId;
int? id;
String? title;
String? body;

PostsModel({this.userId, this.id, this.title, this.body});

PostsModel.fromJson(Map<String, dynamic> json) {
userId = json['userId'];
id = json['id'];
title = json['title'];
body = json['body'];
}

Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['userId'] = this.userId;
data['id'] = this.id;
data['title'] = this.title;
data['body'] = this.body;
return data;
}
}

Step 3: API Call

We define a future method getPostApi() to make an HTTP GET request to the servers, It will return as data and we will return as List of post to show in widget.

 Future<List<PostsModel>> getPostApi ()async{

try {
final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts')) ;
final body = json.decode(response.body) as List;
if(response.statusCode == 200) {

return body.map((dynamic json) {
final map = json as Map<String, dynamic>;
return PostsModel(
id: map['id'] as int,
title: map['title'] as String,
body: map['body'] as String,
);
}).toList();
}
} on SocketException {
await Future.delayed(const Duration(milliseconds: 1800));
throw Exception('No Internet Connection');
} on TimeoutException {
throw Exception('');
}
throw Exception('error fetching data');

}

Step 4: Dropdown Widget

var newData, variable will store the selected value in the drop down, note i am showing ID but you show any value you like.

We are using Future builder because we have future getPostApi() method

FutureBuilder<List<PostsModel>>(
future: getPostApi(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return DropdownButton(
// Initial Value
value: newData,
hint: Text('Select value'),
isExpanded: true,
// Down Arrow Icon
icon: const Icon(Icons.keyboard_arrow_down),

// Array list of items
items: snapshot.data!.map((item) {
return DropdownMenuItem(
value: item.id,
child: Text(item.id.toString()),
);
}).toList(),
onChanged: (value) {
newData = value ;
setState(() {

});
},

);
} else {
return Center(child: const CircularProgressIndicator());
}
},

Complete Source Code:




import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import '../Models/posts_model.dart';

class DropDownApi extends StatefulWidget {
const DropDownApi({Key? key}) : super(key: key);

@override
State<DropDownApi> createState() => _DropDownApiState();
}

class _DropDownApiState extends State<DropDownApi> {




Future<List<PostsModel>> getPostApi ()async{

try {
final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts')) ;
final body = json.decode(response.body) as List;
if(response.statusCode == 200) {

return body.map((dynamic json) {
final map = json as Map<String, dynamic>;
return PostsModel(
id: map['id'] as int,
title: map['title'] as String,
body: map['body'] as String,
);
}).toList();
}
} on SocketException {
await Future.delayed(const Duration(milliseconds: 1800));
throw Exception('No Internet Connection');
} on TimeoutException {
throw Exception('');
}
throw Exception('error fetching data');

}

var newData ;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Dropdown Api'),
),
body: Padding(
padding: const EdgeInsets.symmetric(horizontal: 20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: [
FutureBuilder<List<PostsModel>>(
future: getPostApi(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return DropdownButton(
// Initial Value
value: newData,
hint: Text('Select value'),
isExpanded: true,
// Down Arrow Icon
icon: const Icon(Icons.keyboard_arrow_down),

// Array list of items
items: snapshot.data!.map((item) {
return DropdownMenuItem(
value: item.id,
child: Text(item.id.toString()),
);
}).toList(),
onChanged: (value) {
newData = value ;
setState(() {

});
},

);
} else {
return Center(child: const CircularProgressIndicator());
}
},
)
],
),
),
);
}
}

--

--

Axiftaj
Axiftaj

Written by Axiftaj

Hello, this is Asif Taj a tech enthusiasts providing the quality services for the Android and iOS apps development, UI/UX Research and Designs, and Video ads.

Responses (1)