Implementasi OOP di flutter

Tutorial Flutter: Implementasi CRUD Produk dengan OOP

Daftar Isi

  1. Pengenalan

  2. Persiapan Proyek

  3. Membuat Model Produk

  4. Implementasi Service Layer

  5. Membangun Antarmuka Pengguna

1. Pengenalan

1.1 Apa yang akan kita pelajari?

Dalam tutorial ini, kita akan membuat aplikasi manajemen produk sederhana menggunakan Flutter dengan pendekatan Object-Oriented Programming (OOP). Aplikasi ini akan mencakup operasi dasar CRUD (Create, Read, Update, Delete).

1.2 Prasyarat

  • Dasar pemrograman Dart/Flutter

  • Flutter SDK terinstal

  • IDE (VSCode/Android Studio)

  • Pemahaman dasar OOP

2. Persiapan Proyek

2.1 Membuat Proyek Baru

flutter create product_management
cd product_management

2.2 Struktur Folder

Buat struktur folder berikut:

lib/
  ├── models/
  │   └── product.dart
  ├── services/
  │   └── product_service.dart
  ├── screens/
  │   └── product_page.dart
  └── main.dart

3. Membuat Model Produk

3.1 Implementasi Product Model

Buat file lib/models/product.dart:

// lib/models/product.dart
class Product {
  String? id;
  String name;
  String description;
  double price;
  int stock;

  Product({
    this.id,
    required this.name,
    required this.description,
    required this.price,
    required this.stock,
  });

  // Konversi dari Product ke Map
  Map<String, dynamic> toMap() {
    return {
      'id': id,
      'name': name,
      'description': description,
      'price': price,
      'stock': stock,
    };
  }

  // Membuat Product dari Map
  factory Product.fromMap(Map<String, dynamic> map) {
    return Product(
      id: map['id'],
      name: map['name'],
      description: map['description'],
      price: map['price'],
      stock: map['stock'],
    );
  }
}

3.2 Penjelasan Model

  • Properti:

    • id: Identifier unik produk (opsional, diisi saat create)

    • name: Nama produk

    • description: Deskripsi produk

    • price: Harga produk

    • stock: Stok produk

  • Method:

    • toMap(): Mengkonversi objek Product ke bentuk Map

    • fromMap(): Factory constructor untuk membuat objek Product dari Map

4. Implementasi Service Layer

4.1 Product Service

Buat file lib/services/product_service.dart:

// lib/services/product_service.dart
import '../models/product.dart';

class ProductService {
  // Simulasi database menggunakan List
  final List<Product> _products = [];

  // Create: Menambah produk baru
  void addProduct(Product product) {
    product.id = DateTime.now().millisecondsSinceEpoch.toString();
    _products.add(product);
  }

  // Read: Mendapatkan semua produk
  List<Product> getAllProducts() {
    return _products;
  }

  // Read: Mendapatkan produk berdasarkan ID
  Product? getProductById(String id) {
    try {
      return _products.firstWhere((product) => product.id == id);
    } catch (e) {
      return null;
    }
  }

  // Update: Memperbarui produk
  void updateProduct(Product updatedProduct) {
    final index = _products.indexWhere((product) => product.id == updatedProduct.id);
    if (index != -1) {
      _products[index] = updatedProduct;
    }
  }

  // Delete: Menghapus produk
  void deleteProduct(String id) {
    _products.removeWhere((product) => product.id == id);
  }
}

4.2 Penjelasan Service Layer

Service layer bertanggung jawab untuk:

  1. Manajemen Data:

    • Menyimpan data produk dalam List

    • Mengatur operasi CRUD

  2. Operasi CRUD:

    • Create: addProduct()

    • Read: getAllProducts() dan getProductById()

    • Update: updateProduct()

    • Delete: deleteProduct()

5. Membangun Antarmuka Pengguna

5.1 Implementasi Product Page

Buat file lib/screens/product_page.dart:

// lib/screens/product_page.dart
import 'package:flutter/material.dart';
import '../models/product.dart';
import '../services/product_service.dart';

class ProductPage extends StatefulWidget {
  @override
  _ProductPageState createState() => _ProductPageState();
}

class _ProductPageState extends State<ProductPage> {
  final ProductService _productService = ProductService();
  final _formKey = GlobalKey<FormState>();
  
  // Controllers untuk form
  final _nameController = TextEditingController();
  final _descriptionController = TextEditingController();
  final _priceController = TextEditingController();
  final _stockController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Manajemen Produk'),
      ),
      body: Column(
        children: [
          _buildForm(),
          _buildProductList(),
        ],
      ),
    );
  }

  // Widget Form
  Widget _buildForm() {
    return Padding(
      padding: EdgeInsets.all(16.0),
      child: Form(
        key: _formKey,
        child: Column(
          children: [
            TextFormField(
              controller: _nameController,
              decoration: InputDecoration(labelText: 'Nama Produk'),
              validator: (value) {
                if (value == null || value.isEmpty) {
                  return 'Nama produk harus diisi';
                }
                return null;
              },
            ),
            TextFormField(
              controller: _descriptionController,
              decoration: InputDecoration(labelText: 'Deskripsi'),
            ),
            TextFormField(
              controller: _priceController,
              decoration: InputDecoration(labelText: 'Harga'),
              keyboardType: TextInputType.number,
              validator: (value) {
                if (value == null || value.isEmpty) {
                  return 'Harga harus diisi';
                }
                return null;
              },
            ),
            TextFormField(
              controller: _stockController,
              decoration: InputDecoration(labelText: 'Stok'),
              keyboardType: TextInputType.number,
              validator: (value) {
                if (value == null || value.isEmpty) {
                  return 'Stok harus diisi';
                }
                return null;
              },
            ),
            SizedBox(height: 16),
            ElevatedButton(
              onPressed: _addProduct,
              child: Text('Tambah Produk'),
            ),
          ],
        ),
      ),
    );
  }

  // Widget Daftar Produk
  Widget _buildProductList() {
    return Expanded(
      child: ListView.builder(
        itemCount: _productService.getAllProducts().length,
        itemBuilder: (context, index) {
          final product = _productService.getAllProducts()[index];
          return ListTile(
            title: Text(product.name),
            subtitle: Text('${product.description}\nHarga: Rp${product.price} | Stok: ${product.stock}'),
            trailing: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                IconButton(
                  icon: Icon(Icons.edit),
                  onPressed: () => _showEditDialog(product),
                ),
                IconButton(
                  icon: Icon(Icons.delete),
                  onPressed: () => _deleteProduct(product),
                ),
              ],
            ),
          );
        },
      ),
    );
  }

  // Method untuk menambah produk
  void _addProduct() {
    if (_formKey.currentState!.validate()) {
      final product = Product(
        name: _nameController.text,
        description: _descriptionController.text,
        price: double.parse(_priceController.text),
        stock: int.parse(_stockController.text),
      );

      setState(() {
        _productService.addProduct(product);
      });

      _resetForm();
    }
  }

  // Method untuk menghapus produk
  void _deleteProduct(Product product) {
    setState(() {
      _productService.deleteProduct(product.id!);
    });
  }

  // Method untuk menampilkan dialog edit
  void _showEditDialog(Product product) {
    _nameController.text = product.name;
    _descriptionController.text = product.description;
    _priceController.text = product.price.toString();
    _stockController.text = product.stock.toString();

    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text('Edit Produk'),
        content: Form(
          key: _formKey,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              TextFormField(
                controller: _nameController,
                decoration: InputDecoration(labelText: 'Nama Produk'),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return 'Nama produk harus diisi';
                  }
                  return null;
                },
              ),
              TextFormField(
                controller: _descriptionController,
                decoration: InputDecoration(labelText: 'Deskripsi'),
              ),
              TextFormField(
                controller: _priceController,
                decoration: InputDecoration(labelText: 'Harga'),
                keyboardType: TextInputType.number,
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return 'Harga harus diisi';
                  }
                  return null;
                },
              ),
              TextFormField(
                controller: _stockController,
                decoration: InputDecoration(labelText: 'Stok'),
                keyboardType: TextInputType.number,
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return 'Stok harus diisi';
                  }
                  return null;
                },
              ),
            ],
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: Text('Batal'),
          ),
          ElevatedButton(
            onPressed: () => _updateProduct(product),
            child: Text('Simpan'),
          ),
        ],
      ),
    );
  }

  // Method untuk update produk
  void _updateProduct(Product product) {
    if (_formKey.currentState!.validate()) {
      final updatedProduct = Product(
        id: product.id,
        name: _nameController.text,
        description: _descriptionController.text,
        price: double.parse(_priceController.text),
        stock: int.parse(_stockController.text),
      );

      setState(() {
        _productService.updateProduct(updatedProduct);
      });

      Navigator.pop(context);
      _resetForm();
    }
  }

  // Method untuk reset form
  void _resetForm() {
    _nameController.clear();
    _descriptionController.clear();
    _priceController.clear();
    _stockController.clear();
  }

  @override
  void dispose() {
    _nameController.dispose();
    _descriptionController.dispose();
    _priceController.dispose();
    _stockController.dispose();
    super.dispose();
  }
}

5.2 Menghubungkan ke Main App

Update file lib/main.dart:

// lib/main.dart
import 'package:flutter/material.dart';
import 'screens/product_page.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Product Management',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: ProductPage(),
    );
  }
}
flutter run

coding full

Last updated