Introduction
Flutter, a popular open-source framework for building cross-platform mobile applications, empowers developers to create feature-rich apps. To build data-driven applications, integrating with APIs is essential. By combining Flutter’s reactive framework with the powerful state management library “Provider,” you can seamlessly handle API calls with ease and efficiency.
In this comprehensive step-by-step guide, we will walk you through every aspect of making API calls using Provider in Flutter. From project setup to handling complex API requests, this article will equip you with the knowledge and complete code examples to master API integration in your Flutter projects.
Let’s get started!
Step 1: Setting up Flutter Environment
Before diving into API calls, make sure you have Flutter installed and set up on your system. Follow these steps:
- Download and install Flutter by following the official documentation for your specific operating system.
- Add the Flutter SDK to your system’s PATH to use Flutter commands globally.
Step 2: Creating a New Flutter Project
Now, let’s create a new Flutter project:
- Open a terminal or command prompt.
- Use the following command to create a new Flutter project:
flutter create flutter_api_demo
- Navigate to the project directory:
cd flutter_api_demo
Step 3: Adding Dependencies
To work with Provider and make API calls, you need to add the required dependencies to your pubspec.yaml
file:
dependencies:
flutter:
sdk: flutter
provider: ^5.0.0
http: ^0.13.3
Run flutter pub get
in the terminal to download and install the new dependencies.
Step 4: Designing the API Service
To interact with an API, you need to define models for the data and create a service to handle API requests.
- Create a new file named
data_model.dart
in thelib
directory:
// lib/data_model.dart
class DataModel {
final int id;
final String name;
DataModel({required this.id, required this.name});
factory DataModel.fromJson(Map<String, dynamic> json) {
return DataModel(
id: json['id'],
name: json['name'],
);
}
}
Create another file named api_service.dart
in the lib
directory:
// lib/api_service.dart
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'data_model.dart';
class ApiService {
static const String apiUrl = 'https://api.example.com/data';
Future<List<DataModel>> fetchData() async {
try {
final response = await http.get(Uri.parse(apiUrl));
if (response.statusCode == 200) {
final List<dynamic> responseData = json.decode(response.body);
return responseData.map((json) => DataModel.fromJson(json)).toList();
} else {
throw Exception('Failed to load data');
}
} catch (e) {
throw Exception('Failed to fetch data: $e');
}
}
}
Step 5: Implementing Provider for State Management
Provider is a powerful state management library that simplifies data handling in Flutter apps. Let’s implement Provider in our project:
- In the
lib
directory, create a new file namedapi_provider.dart
:
// lib/api_provider.dart
import 'package:flutter/material.dart';
import 'data_model.dart';
import 'api_service.dart';
class ApiProvider extends ChangeNotifier {
List<DataModel> _data = [];
List<DataModel> get data => _data;
ApiService _apiService = ApiService();
Future<void> fetchData() async {
try {
_data = await _apiService.fetchData();
notifyListeners();
} catch (e) {
throw Exception('Failed to fetch data: $e');
}
}
}
Step 6: Creating the Main Application Widget
Now, let’s create the main application widget that utilizes Provider and displays the API data:
- Open the
lib/main.dart
file and replace its content with the following code:
// lib/main.dart
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'api_provider.dart';
void main() {
runApp(
ChangeNotifierProvider<ApiProvider>(
create: (context) => ApiProvider(),
child: MyApp(),
),
);
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Flutter API Call using Provider'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Consumer<ApiProvider>(
builder: (context, apiProvider, _) {
if (apiProvider.data.isEmpty) {
return CircularProgressIndicator();
} else {
return ListView.builder(
shrinkWrap: true,
itemCount: apiProvider.data.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(apiProvider.data[index].name),
);
},
);
}
},
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
// Fetch data when the floating action button is pressed
Provider.of<ApiProvider>(context, listen: false).fetchData();
},
child: Icon(Icons.refresh),
),
),
);
}
}
Step 7: Run the App
That’s it! Your Flutter app with API calls using Provider is now ready. To test the app, run the following command in the terminal:
flutter run
The app will launch in the selected emulator or physical device, and when you press the “Refresh” button, it will fetch data from the API and display it in a list.
Conclusion
Congratulations! You have successfully learned how to make Flutter API calls using Provider in a step-by-step manner. By following this guide, you can build powerful, data-driven Flutter applications with efficient API integration and state management.
Remember to handle error states, loading indicators, and other advanced scenarios based on your specific project requirements. Happy coding!
Related Searches: api call, api call using provider, how to call api, call api using provider, how to call api using provider