Tutorial Flutter dengan Laravel Rest API #6: Delete Data di Flutter dari Rest API

Halo teman-teman sebelumnya kita sudah belajar edit dan update data, pada artikel kali ini kita belajar bagaimana cara hapus data melalu Rest API.

Langkah 1 – Membuat Fungsi Delete

Untuk langkah pertama kalian buat fungsi delete, buka file home.dart dan ketikan kode berikut pada class _HomeState

class _HomeState extends State<Home> {
.......
 Future<void> _deletePost(int postId) async {
    try {
      final response = await _apiService.deletePost(postId);
      if (response) {
        setState(() {
          _posts.removeWhere((post) => post.id == postId);
        });
        _loadMorePosts();
      }
    } catch (e) {
      throw Exception(e.toString());
    }
  }
............
........
}

Pada fungsi _deletePost(int postId) ini di beri parameter yang bernilai int yang dimana isi parameter tesebut id dari post, lalu kita kirim ke server dengan fungsi _apiService.deletePost(postId).

Jangan lupa kita juga panggil fungsi _deletePost pada widget buton icon delete, hapus comment //TODO action delete post sehingga menjadi berikut:

.......
Positioned(
                    bottom: 2,
                    right: 2,
                    child: IconButton(
                      onPressed: () => _deletePost(post.id),
                      icon: const Icon(Icons.delete_rounded),
                    ),
                  )
.............

Sehingga keseluruhan file pada home.dart menjadi berikut:

import 'package:flutter/material.dart';
import 'package:flutter_pemula/api/repository.dart';
import 'package:flutter_pemula/component/post_view.dart';
import 'package:flutter_pemula/model/post.dart';
import 'package:flutter_pemula/screen/add_edit_post_screen.dart';

class Home extends StatefulWidget {
  final String title;

  const Home({
    super.key,
    required this.title,
  });

  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> {
  final ScrollController _scrollController = ScrollController();
  final Repository _apiService = Repository();

  final List<Post> _posts = [];
  bool _isLoading = false;
  bool _hasMore = true;
  int _currentPage = 1;

  @override
  void initState() {
    super.initState();
    _loadPosts();
    _scrollController.addListener(() {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        _loadMorePosts();
      }
    });
  }

  Future<void> _loadPosts() async {
    setState(() {
      _isLoading = true;
    });

    try {
      final result = await _apiService.fetchPosts(_currentPage);
      setState(() {
        _currentPage++;
        _posts.addAll(result['posts']);
        _hasMore = result['nextPageUrl'] != null;
      });
    } catch (e) {
      throw Exception(e.toString());
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  Future<void> _loadMorePosts() async {
    if (_isLoading || !_hasMore) return;

    setState(() {
      _isLoading = true;
    });

    try {
      final result = await _apiService.fetchPosts(_currentPage);
      setState(() {
        _currentPage++;
        _posts.addAll(result['posts']);
        _hasMore = result['nextPageUrl'] != null;
      });
    } catch (e) {
      throw Exception(e.toString());
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  Future<void> _deletePost(int postId) async {
    try {
      final response = await _apiService.deletePost(postId);
      if (response) {
        setState(() {
          _posts.removeWhere((post) => post.id == postId);
        });
        _loadMorePosts();
      }
    } catch (e) {
      throw Exception(e.toString());
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
      ),
      body: _buildPostList(),
      floatingActionButton: FloatingActionButton(
        onPressed: () async {
          var result = await Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => const AddEditPostScreen(),
            ),
          );
          if (result == true) {
            _currentPage = 1;
            _posts.clear();
            _hasMore = true;
            _loadPosts();
          }
        },
        child: const Icon(Icons.add),
      ),
    );
  }

  Widget _buildPostList() {
    return ListView.builder(
      controller: _scrollController,
      itemCount: _posts.length + (_hasMore ? 1 : 0),
      itemBuilder: (context, index) {
        if (index == _posts.length) {
          return const Center(child: CircularProgressIndicator());
        }
        final post = _posts[index];

        return Padding(
          padding: const EdgeInsets.all(8.0),
          child: Card.filled(
            clipBehavior: Clip.hardEdge,
            child: InkWell(
              onTap: () {
                // Todo action ke detail post
              },
              child: Stack(
                children: [
                  PostView(post: post),
                  Positioned(
                    top: 2,
                    right: 2,
                    child: IconButton(
                      onPressed: () async {
                        final result = await Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) => AddEditPostScreen(post: post),
                          ),
                        );

                        if (result == true) {
                          _currentPage = 1;
                          _posts.clear();
                          _hasMore = true;
                          _loadPosts();
                        }
                      },
                      icon: const Icon(Icons.edit_rounded),
                    ),
                  ),
                  Positioned(
                    bottom: 2,
                    right: 2,
                    child: IconButton(
                      onPressed: () => _deletePost(post.id),
                      icon: const Icon(Icons.delete_rounded),
                    ),
                  )
                ],
              ),
            ),
          ),
        );
      },
    );
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }
}

Sekarang kalian jalankan dan tap pada icon delete jika terhapus berarti kalian sudah berhasil.

Kesimpulan

Pada artikel kali ini, kita belajar bagaimana cara menghapus data melalui Rest API. Bila teman-teman menemui kendala atau error kalian bisa bertanya di grup telegram santrikoding atau memberikan komentar dibawah.

Untuk Source Code kalian bisa ambil di link berikut https://github.com/hunt3r6/flutter-rest-api


Membangun Website dan Aplikasi Android Desa Dengan Laravel, React.js dan React Native

Membangun Aplikasi dan Website News Dengan Laravel, React.js dan Android

Faisal Mahadi
Faisal Mahadi

Mobile Apps Developer | Android Enthusiast | Keep Learning | Android Dev
Serta Owner Hariankoding.com

Articles: 8