Here’s an example of how you can implement CRUD operations using the http package in Flutter wrapped up in a Remote Data Source. This example assumes that your backend uses a REST API.
First, add the http package to your pubspec.yaml file:
dependencies:
flutter:
sdk: flutter
http: ^0.2.2
Then, run flutter pub get
to install the package.
Now, let’s create a data model class for your remote application:
// models/remote_application.dart
class RemoteApplication {
int id;
String name;
RemoteApplication({required this.id, required this.name});
factory RemoteApplication.fromJson(Map<String, dynamic> json) {
return RemoteApplication(
id: json['id'],
name: json['name'],
);
}
Map<String, dynamic> toJson() {
return {
'id': id,
'name': name,
};
}
}
Next, let’s create a remote data source class that handles CRUD operations:
// services/remote_data_source.dart
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'odels/remote_application.dart';
class RemoteDataSource {
final String _baseUrl = 'https://your-api.com/applications';
final http.Client _client;
RemoteDataSource({required http.Client client}) : _client = client;
Future<List<RemoteApplication>> getApplications() async {
final response = await _client.get(Uri.parse('$_baseUrl'));
if (response.statusCode == 200) {
final jsonData = jsonDecode(response.body);
return jsonData
.map((json) => RemoteApplication.fromJson(json))
.toList();
} else {
throw Exception('Failed to load applications');
}
}
Future<RemoteApplication> getApplication(int id) async {
final response = await _client.get(Uri.parse('$_baseUrl/$id'));
if (response.statusCode == 200) {
return RemoteApplication.fromJson(jsonDecode(response.body));
} else {
throw Exception('Failed to load application');
}
}
Future<void> createApplication(RemoteApplication application) async {
final response = await _client.post(Uri.parse('$_baseUrl'),
headers: {'Content-Type': 'application/json'},
body: jsonEncode(application.toJson()));
if (response.statusCode!= 201) {
throw Exception('Failed to create application');
}
}
Future<void> updateApplication(RemoteApplication application) async {
final response = await _client.put(Uri.parse('$_baseUrl/${application.id}'),
headers: {'Content-Type': 'application/json'},
body: jsonEncode(application.toJson()));
if (response.statusCode!= 200) {
throw Exception('Failed to update application');
}
}
Future<void> deleteApplication(int id) async {
final response = await _client.delete(Uri.parse('$_baseUrl/$id'));
if (response.statusCode!= 204) {
throw Exception('Failed to delete application');
}
}
}
Finally, let’s create a repository class that uses the remote data source to handle CRUD operations:
// repositories/applications_repository.dart
import 'package:flutter/services.dart' show rootBundle;
import 'dart:convert';
import 'ervices/remote_data_source.dart';
import 'odels/remote_application.dart';
class ApplicationsRepository {
final RemoteDataSource _dataSource;
ApplicationsRepository({required RemoteDataSource dataSource})
: _dataSource = dataSource;
Future<List<RemoteApplication>> getApplications() async {
return await _dataSource.getApplications();
}
Future<RemoteApplication> getApplication(int id) async {
return await _dataSource.getApplication(id);
}
Future<void> createApplication(RemoteApplication application) async {
await _dataSource.createApplication(application);
}
Future<void> updateApplication(RemoteApplication application) async {
await _dataSource.updateApplication(application);
}
Future<void> deleteApplication(int id) async {
await _dataSource.deleteApplication(id);
}
}
You can use the repository class in your Flutter app like this:
// main.dart
import 'package:flutter/material.dart';
import 'epositories/applications_repository.dart';
void main() async {
final http.Client client = http.Client();
final RemoteDataSource dataSource = RemoteDataSource(client: client);
final ApplicationsRepository repository =
ApplicationsRepository(dataSource: dataSource);
runApp(MyApp(repository: repository));
}
class MyApp extends StatelessWidget {
final ApplicationsRepository _repository;
MyApp({required this._repository});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Remote App',
home: MyHomePage(repository: _repository),
);
}
}
class MyHomePage extends StatefulWidget {
final ApplicationsRepository _repository;
MyHomePage({required this._repository});
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
List<RemoteApplication> _applications = [];
@override
void initState() {
super.initState();
_loadApplications();
}
Future<void> _loadApplications() async {
final applications = await widget._repository.getApplications();
setState(() {
_applications = applications;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Remote App'),
),
body: ListView.builder(
itemCount: _applications.length,
itemBuilder: (context, index) {
final application = _applications[index];
return ListTile(
title: Text(application.name),
subtitle: Text('ID: ${application.id}'),
);
},
),
);
}
}
This example demonstrates how to use the http package in Flutter for CRUD operations with a remote data source. The repository class handles the business logic, and the remote data source class interacts with the API to perform CRUD operations. For more Flutter Articles – check out – https://programtom.com/dev/category/software-development/flutter/