Skip to content

Software Development at Program Tom LTD

Place for coding, programming, development and software in general.

Menu
  • Blog
  • PDF Booklets
  • Dev Utils & Content
  • Java Spring Boot Or Web Apps
  • English
    • български
    • English
    • Español
    • Português
    • हिन्दी
    • Русский
    • Deutsch
    • Français
    • Italiano
    • العربية
  • About Us
Menu
Flutter Remote CRUD Data Source - using the http package

Flutter Remote CRUD Data Source – using the http package

Posted on December 12, 2024December 23, 2024 by Toma Velev

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/

  • Feature Flags – Enable Functionality from the BackEnd
  • Integrating xAI Grok API with Spring Boot
  • How to Progresively Integrate AI
  • What is an AI Agent
  • Flutter image scaling

Categories

  • Apps (22)
  • ChatGPT (23)
  • Choosing a Framework (38)
  • Flutter (256)
  • Graphical User Interface (14)
  • Marketing (116)
  • Software Development (281)
  • Spring (44)
  • StartUp (22)
  • Uncategorized (14)
  • Uncategorized (4)
  • Vaadin (14)

Tags

Algorithms (9) crypto (29) flutterdev (39) General (86) Java (7) QR & Bar Codes (3) Software Dev Choices (33) Spring Boot (1) standards (1) Theme (3) User Authentication & Authorization (9) User Experience (10) Utilities (19) WordPress (11)

Product categories

  • All Technologies (84)
    • Flutter Apps (24)
    • GPT (4)
    • Java (38)
    • Native Android (3)
    • PHP (9)
    • Spring (Boot) / Quarkus (35)
    • Utils (15)
    • Vaadin 24+ (27)
    • Vaadin 8 (1)
  • Apps (18)
    • Employees DB (1)
    • Notes (6)
    • Personal Budget (1)
    • Recipes Book (1)
    • Stuff Organizer (1)
    • To-Do (2)
  • PDF Books (3)
  • Source Code Generators (8)

Recent Posts

  • Feature Flags – Enable Functionality from the BackEnd
  • Integrating xAI Grok API with Spring Boot
  • How to Progresively Integrate AI
  • What is an AI Agent
  • Flutter image scaling

Post Categories

  • Apps (22)
  • ChatGPT (23)
  • Choosing a Framework (38)
  • Flutter (256)
  • Graphical User Interface (14)
  • Marketing (116)
  • Software Development (281)
  • Spring (44)
  • StartUp (22)
  • Uncategorized (14)
  • Uncategorized (4)
  • Vaadin (14)