httpagent 0.0.9
httpagent: ^0.0.9 copied to clipboard
httpagent is a comprehensive library of custom HTTP API calling for Flutter.
httpagent #
httpagent A simple and easy-to-use Dart package for making HTTP requests. With support for GET, POST, PUT, DELETE, and multipart POST requests, httpagent makes it straightforward to handle JSON data, headers (including global default headers and request-specific overrides), and callbacks for task completions and errors.
Features #
- Global Default Headers: Set headers that apply to all requests using ApiHeaders.setDefaultHeaders.
- Flexible Requests: Easily perform GET, POST, PUT, DELETE, and multipart POST requests.
- Custom Headers Per Request: Merge global headers with extra headers or ignore defaults completely.
- JSON Handling: Automatically encode request bodies to JSON.
- Callback Functions: Implement the NetworkResponse interface to handle successful responses and errors.
Installation #
Add httpagent to your pubspec.yaml file:
dependencies:
httpagent: ^0.0.9
Then run:
flutter pub get
Usage #
Import the package in your Dart file:
import 'package:httpagent/httpagent.dart';
NetworkUtils Class #
The NetworkUtils class is used to perform HTTP requests. It requires a URL, a caller identifier, and a callback object that implements the NetworkResponce interface.
Example Usage #
GET Request
Future<void> getData() async {
NetworkUtils task = NetworkUtils(
"https://example.com/api/users",
'getData',
this,
useDefaultHeaders: true, // Using global headers
);
await task.get();
}
POST Request
Future<void> postData() async {
NetworkUtils task = NetworkUtils(
"https://example.com/api/users",
'postData',
this,
);
await task.post(data: {'name': 'John Doe', 'email': 'john@example.com'});
}
PUT Request
Future<void> putData() async {
NetworkUtils task = NetworkUtils(
"https://example.com/api/users/1",
'putData',
this,
);
await task.put(data: {'name': 'Updated Name'});
}
DELETE Request
Future<void> deleteData() async {
NetworkUtils task = NetworkUtils(
"https://example.com/api/users/1",
'deleteData',
this,
);
await task.delete();
}
Multipart POST Request
Future<void> uploadFile() async {
NetworkUtils task = NetworkUtils(
"https://example.com/api/upload",
'uploadFile',
this,
useDefaultHeaders: true,
);
await task.multipartPost(
data: {'description': 'File Upload'},
filePath: '/path/to/file.jpg',
headers: {
'File-Token': 'SecureUpload123',
},
);
}
Example #
For a complete working example, check out the Example Folder.
NetworkResponse Interface #
The NetworkResponse interface defines two methods:
onTaskComplete(String result, String caller): Called when a request completes successfully.onTaskError(String error, String caller): Called when a request fails.
Implement this interface in your class to handle responses and errors.
httpagent simplifies HTTP requests in Flutter and Dart, making API integration easier and more manageable!
🙌 Contributors #
A huge thanks to these amazing people: