Fetching data from a REST API is a common task in modern mobile applications. Flutter, a popular framework for building cross-platform mobile apps, provides robust tools for handling network requests. In this article, we’ll explore how to fetch data from the REST API provided by JSONPlaceholder and display it in a Flutter application.
Setting Up Your Flutter Project
First, create a new Flutter project if you don’t already have one. You can do this by running the following command in your terminal:
flutter create fetch_data_example
cd fetch_data_example
To make HTTP requests, we need to add the ‘http
‘ package to our project. Open the ‘pubspec.yaml
‘ file and add the dependency under dependencies
:
dependencies:
flutter:
sdk: flutter
http: ^0.14.0
Run flutter pub get
to install the new dependency.
Making the HTTP Request
Create a new file, ‘user_model.dart
‘, to define a model for the user data:
class User {
final int id;
final String name;
final String username;
final String email;
User({
required this.id,
required this.name,
required this.username,
required this.email,
});
factory User.fromJson(Map<String, dynamic> json) {
return User(
id: json['id'],
name: json['name'],
username: json['username'],
email: json['email'],
);
}
}
Next, create another file, api_service.dart
, to handle the HTTP requests:
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'user_model.dart';
class ApiService {
static const String url = 'https://jsonplaceholder.typicode.com/users';
Future<List<User>> fetchUsers() async {
final response = await http.get(Uri.parse(url));
if (response.statusCode == 200) {
List<dynamic> data = json.decode(response.body);
List<User> users = data.map((user) => User.fromJson(user)).toList();
return users;
} else {
throw Exception('Failed to load users');
}
}
}
Displaying the Data in the UI
Now, let’s display the fetched data in the Flutter app. Open the ‘main.dart
‘ file and replace its contents with the following code:
import 'package:flutter/material.dart';
import 'api_service.dart';
import 'user_model.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Fetch Data Example',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
late Future<List<User>> futureUsers;
@override
void initState() {
super.initState();
futureUsers = ApiService().fetchUsers();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Fetch Data Example'),
),
body: FutureBuilder<List<User>>(
future: futureUsers,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(child: CircularProgressIndicator());
} else if (snapshot.hasError) {
return Center(child: Text('Error: ${snapshot.error}'));
} else if (!snapshot.hasData) {
return Center(child: Text('No data found'));
} else {
List<User> users = snapshot.data!;
return ListView.builder(
itemCount: users.length,
itemBuilder: (context, index) {
User user = users[index];
return ListTile(
title: Text(user.name),
subtitle: Text(user.email),
);
},
);
}
},
),
);
}
}
Running the App
Now, run the app using ‘flutter run
‘. You should see a list of users fetched from the JSONPlaceholder API displayed in a ListView. The app handles loading states, and errors, and displays the data efficiently using Flutter’s ‘FutureBuilder
‘.
In this article, we used the ‘http
‘ package to make network requests created a model to represent the data and displayed the data using Flutter’s widgets. This approach is scalable and can be extended to handle more complex APIs and data structures, making it a valuable skill for any Flutter developer.