REST API

REST itu kependakan dari REpresentational State Transfer yang merupakan standar arsitektur berbasis web yang menggunakan protokol HTTP untuk berkomunikasi data.

Software

1. Web Server

or

2. API Development ( POSTMAN)

Text

MariaDB

MariaDB merupakan versi pengembangan terbuka dan mandiri dari MySQL. Sejak diakuisisinya MySQL oleh Oracle pada September 2010, Monty Program sebagai penulis awal kode sumber MySQL memisahkan diri dari pengembangan dan membuat versi yang lebih mandiri yakni MariaDB.

DATABASE

1. Buka Mysql/Phpmyadmin, buat database dengan nama : catatanku

 

2. Buat tabel dengan nama tb_kategori_catatan

 

CREATE TABLE `tb_kategori_catatan` (
  `id_kategori` int(11) NOT NULL,
  `nama_kategori` varchar(125) NOT NULL,
  `icon_kategori` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

3. Buat tabel dengan nama tb_catatan_mutasi

 

CREATE TABLE `tb_catatan_mutasi` (
  `id_mutasi` int(11) NOT NULL,
  `id_device` text DEFAULT NULL,
  `id_kategori` int(10) DEFAULT NULL,
  `mutasi` char(3) DEFAULT NULL,
  `judul` varchar(30) DEFAULT NULL,
  `deskripsi` text DEFAULT NULL,
  `nominal` double DEFAULT NULL,
  `tgl` date DEFAULT NULL,
  `create_at` timestamp NOT NULL DEFAULT current_timestamp(),
  `update_at` timestamp NOT NULL DEFAULT current_timestamp()
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
CREATE TABLE `tb_token` (
  `id_token` int(11) NOT NULL,
  `id_device` text DEFAULT NULL,
  `token` text NOT NULL,
  `created_date` timestamp NOT NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

4. Buat tabel dengan nama tb_token

 

Download Database

-- phpMyAdmin SQL Dump
-- version 4.8.3
-- https://www.phpmyadmin.net/
--
-- Host: localhost:3306
-- Generation Time: Dec 13, 2019 at 09:19 PM
-- Server version: 5.7.24
-- PHP Version: 7.2.11

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `catatanku`
--

-- --------------------------------------------------------

--
-- Table structure for table `tb_catatan_mutasi`
--

CREATE TABLE `tb_catatan_mutasi` (
  `id_mutasi` int(11) NOT NULL,
  `id_device` text,
  `id_kategori` int(10) DEFAULT NULL,
  `mutasi` char(3) DEFAULT NULL,
  `judul` varchar(30) DEFAULT NULL,
  `deskripsi` text,
  `nominal` double DEFAULT NULL,
  `tgl` date DEFAULT NULL,
  `create_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `update_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

-- --------------------------------------------------------

--
-- Table structure for table `tb_kategori_catatan`
--

CREATE TABLE `tb_kategori_catatan` (
  `id_kategori` int(11) NOT NULL,
  `nama_kategori` varchar(125) NOT NULL,
  `icon_kategori` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `tb_catatan_mutasi`
--
ALTER TABLE `tb_catatan_mutasi`
  ADD PRIMARY KEY (`id_mutasi`);

--
-- Indexes for table `tb_kategori_catatan`
--
ALTER TABLE `tb_kategori_catatan`
  ADD PRIMARY KEY (`id_kategori`);
COMMIT;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

Framework

CodeIgniter merupakan aplikasi sumber terbuka yang berupa kerangka kerja PHP dengan model MVC untuk membangun website dinamis dengan menggunakan PHP. CodeIgniter memudahkan pengembang web untuk membuat aplikasi web dengan cepat mudah dibandingkan dengan membuatnya dari awal.

Konfigurasi

1. Extrak FIle CI3 ke Folder root server kalian

htdocs / www / public

2. Rename Folder Codeigniter 3.1.11 menjadi catatanku

3. Buka dengan Editor / VsCode

4. Masuk ke Folder application/config/autoload.php

     Tambahkan librari database

5. Masuk ke Folder application/config/database.php

    Isi konfigurasi database

6. Masuk ke Folder application/views/welcome_message.php

    Ubah Menjadi

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?><!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="utf-8">
	<title>Welcome to CodeIgniter</title>

	<style type="text/css">

	::selection { background-color: #E13300; color: white; }
	::-moz-selection { background-color: #E13300; color: white; }

	body {
		background-color: #fff;
		margin: 40px;
		font: 13px/20px normal Helvetica, Arial, sans-serif;
		color: #4F5155;
	}

	a {
		color: #003399;
		background-color: transparent;
		font-weight: normal;
	}

	h1 {
		color: #444;
		background-color: transparent;
		border-bottom: 1px solid #D0D0D0;
		font-size: 19px;
		font-weight: normal;
		margin: 0 0 14px 0;
		padding: 14px 15px 10px 15px;
	}

	code {
		font-family: Consolas, Monaco, Courier New, Courier, monospace;
		font-size: 12px;
		background-color: #f9f9f9;
		border: 1px solid #D0D0D0;
		color: #002166;
		display: block;
		margin: 14px 0 14px 0;
		padding: 12px 10px 12px 10px;
	}

	#body {
		margin: 0 15px 0 15px;
	}

	p.footer {
		text-align: right;
		font-size: 11px;
		border-top: 1px solid #D0D0D0;
		line-height: 32px;
		padding: 0 10px 0 10px;
		margin: 20px 0 0 0;
	}

	#container {
		margin: 10px;
		border: 1px solid #D0D0D0;
		box-shadow: 0 0 8px #D0D0D0;
	}
	</style>
</head>
<body>

<div id="container">
	<h1>Welcome to Catatanku API</h1>

	<div id="body">
		<p>Berikut Adalah API untuk CRUD Catatan Keuangan Harian</p>
	</div>

	<p class="footer">Page rendered in <strong>{elapsed_time}</strong> seconds. <?php echo  (ENVIRONMENT === 'development') ?  'CodeIgniter Version <strong>' . CI_VERSION . '</strong>' : '' ?></p>
</div>

</body>
</html>

3. Jalankan dengan postman

localhost/catatanku

online version kunjungi

4. Masuk ke Folder application/controller

     Buat controller dengan nama : Api.php

<?php

	class API extends CI_Controller
	{

	public function index()
	{
		date_default_timezone_set('Asia/Jakarta');
		error_reporting(E_ALL);
		ini_set('display_errors', 1);
		$this->load->helper('date');
	}

	public function add_token(){ 
		$data       = array();
		$id_device  = $this->input->post('id_device'); 
		$key        = $this->input->post('key'); 
		$token      = bin2hex(random_bytes(64));

		if($key=="fluttertalk02"){
			$sql = "SELECT * FROM tb_token WHERE id_device='$id_device' order by id_token DESC";
			$q = $this->db->query($sql);

			if($q->num_rows() > 0){
				$data['result'] = 'false';
				$data['msg']    = 'Device Already';
			}else{


				$sql        = "INSERT INTO tb_token
							(id_device,token)
							VALUES('$id_device','$token');
						";
					
				$q          = $this->db->query($sql);

				if($q){				
					$data['result']  = 'true';
					$data['msg']     = 'Success Add Token';
				}else{
					$data['result']  = 'false';
					$data['msg']     = 'Failed Add Token';
				}
				
			}
			
		}else{
			$data['result'] = 'false';
			$data['msg']    = 'Invalid Key';
		}



		echo json_encode($data);
	}

	
	public function get_all_token(){ 
		$data  = array();
		$key   = $this->input->post('key');
		
		if($key=="fluttertalk02"){
			$sql  = "SELECT * FROM tb_token order by id_token DESC";
			$q    = $this->db->query($sql);
			if($q->num_rows() > 0){				
				$data['result'] = 'true';
				$data['msg']    = 'Token';
				$data['data']   = $q->result();
			}else{
				$data['result'] = 'false';
				$data['msg']    = 'Tidak ada data';
			}
		}else{
			$data['result'] = 'false';
			$data['msg']    = 'Invalid Key';
		}

		echo json_encode($data);
	}

	public function add_kategori(){ 
		$data = array();

		$token  = $this->input->post('token'); 
		$sql = "SELECT * FROM tb_token WHERE token='$token' order by id_token DESC";
		$q = $this->db->query($sql);
		if($q->num_rows() > 0){

			$id_device      = $this->input->post('id_device'); 
			$nama_kategori  = $this->input->post('nama_kategori'); 
			$icon_kategori  = $this->input->post('icon_kategori'); 

			$sql = "INSERT INTO tb_kategori_catatan
				(nama_kategori,icon_kategori)
				VALUES('$nama_kategori','$icon_kategori')
				";
			$q = $this->db->query($sql);

			if($q){				
				$data['result'] = 'true';
				$data['msg'] = 'Success Add Kategori';
			}else{
				$data['result'] = 'false';
				$data['msg'] = 'Failed Add Kategori';
			}
				
		}else{
			$data['result'] = 'false';
			$data['msg'] = 'Invalid Token';
		}

		echo json_encode($data);
	}


	public function get_all_kategori(){ 
		$data = array();
		
		$token   = $this->input->post('token'); 
		$sql     = "SELECT * FROM tb_token WHERE token='$token' order by id_token DESC";
		$q       = $this->db->query($sql);

		if($q->num_rows() > 0){
			$sql = "SELECT * FROM tb_kategori_catatan";
			$q = $this->db->query($sql);
			if($q->num_rows() > 0){				
				$data['result'] = 'true';
				$data['msg'] = 'Kategori';
				$data['data'] = $q->result();
			}else{
				$data['result'] = 'false';
				$data['msg'] = 'Tidak ada data';
			}			
		}else{
			$data['result'] = 'false';
			$data['msg'] = 'Invalid Token';
		}

		echo json_encode($data);
	}

	public function update_kategori(){ 
		$data = array();

		$token  = $this->input->post('token'); 
		$sql = "SELECT * FROM tb_token WHERE token='$token' order by id_token DESC";
		$q = $this->db->query($sql);
		if($q->num_rows() > 0){

			$id_kategori     = $this->input->post('id_kategori'); 
			$nama_kategori   = $this->input->post('nama_kategori'); 
			$icon_kategori   = $this->input->post('icon_kategori'); 	

			$sql = "UPDATE tb_kategori_catatan
				   SET nama_kategori = '$nama_kategori',
				   	  icon_kategori = '$icon_kategori'
				   WHERE id_kategori='$id_kategori'
			       ";
			$q = $this->db->query($sql);

			if($q){				
				$data['result'] = 'true';
				$data['msg'] = 'Success Update Kategori';
			}else{
				$data['result'] = 'false';
				$data['msg'] = 'Failed Update Kategori';
			}
				
		}else{
			$data['result'] = 'false';
			$data['msg'] = 'Invalid Token';
		}

		echo json_encode($data);
	}

	public function delete_kategori(){ 
		$data = array();

		$token  = $this->input->post('token'); 
		$sql = "SELECT * FROM tb_token WHERE token='$token' order by id_token DESC";
		$q = $this->db->query($sql);
		if($q->num_rows() > 0){

			$id_mutasi     = $this->input->post('id_kategori'); 

			$sql = "DELETE FROM tb_kategori_catatan
				   WHERE id_kategori='$id_kategori'
			       ";
			$q = $this->db->query($sql);

			if($q){				
				$data['result'] = 'true';
				$data['msg'] = 'Success Delete Kategori';
			}else{
				$data['result'] = 'false';
				$data['msg'] = 'Failed Delete Kategori';
			}
				
		}else{
			$data['result'] = 'false';
			$data['msg'] = 'Invalid Token';
		}

		echo json_encode($data);
	}



	public function add_mutasi(){ 
		$data = array();

		$token  = $this->input->post('token'); 
		$sql = "SELECT * FROM tb_token WHERE token='$token' order by id_token DESC";
		$q = $this->db->query($sql);
		if($q->num_rows() > 0){

			$id_device     = $this->input->post('id_device'); 
			$id_kategori   = $this->input->post('id_kategori'); 
			$mutasi        = $this->input->post('mutasi'); 
			$judul         = $this->input->post('judul'); 
			$deskripsi     = $this->input->post('deskripsi'); 
			$nominal       = $this->input->post('nominal'); 
			$tgl           = $this->input->post('tgl'); 	

			$sql = "INSERT INTO tb_catatan_mutasi
				(id_device,id_kategori,mutasi,judul,deskripsi,nominal,tgl)
				VALUES('$id_device','$id_kategori','$mutasi','$judul','$deskripsi','$nominal','$tgl')
				";
			$q = $this->db->query($sql);

			if($q){				
				$data['result'] = 'true';
				$data['msg'] = 'Success Add Catatan';
			}else{
				$data['result'] = 'false';
				$data['msg'] = 'Failed Add Catatan';
			}
				
		}else{
			$data['result'] = 'false';
			$data['msg'] = 'Invalid Token';
		}

		echo json_encode($data);
	}

	public function get_all_mutasi(){ 
		$data = array();

          $id_device = $this->input->post('id_device'); 
		$token  = $this->input->post('token'); 
		$sql = "SELECT * FROM tb_token WHERE token='$token' order by id_token DESC";
		$q = $this->db->query($sql);

		if($q->num_rows() > 0){
			$sql = "SELECT * FROM tb_catatan_mutasi where id_device='$id_device' ORDER BY id_mutasi DESC";
			$q = $this->db->query($sql);
			if($q->num_rows() > 0){				
				$data['result'] = 'true';
				$data['msg']    = 'All Mutasi';
				$data['data']   = $q->result();
			}else{
				$data['result'] = 'false';
				$data['msg']     = 'Tidak ada data';
			}
		}else{
			$data['result'] = 'false';
			$data['msg']    = 'Invalid Token';	
		}

		echo json_encode($data);
	}
	



	public function update_mutasi(){ 
		$data = array();

		$token  = $this->input->post('token'); 
		$sql = "SELECT * FROM tb_token WHERE token='$token' order by id_token DESC";
		$q = $this->db->query($sql);
		if($q->num_rows() > 0){

			$id_mutasi     = $this->input->post('id_mutasi'); 
			$id_device     = $this->input->post('id_device'); 
			$id_kategori   = $this->input->post('id_kategori'); 
			$mutasi        = $this->input->post('mutasi'); 
			$judul         = $this->input->post('judul'); 
			$deskripsi     = $this->input->post('deskripsi'); 
			$nominal       = $this->input->post('nominal'); 
			$tgl           = $this->input->post('tgl'); 	

			$sql = "UPDATE tb_catatan_mutasi
				   SET id_kategori = '$id_kategori',
				   	  mutasi = '$mutasi',
					  judul = '$judul',
					  deskripsi = '$deskripsi',
					  nominal = '$nominal',
					  tgl = '$tgl'
				   WHERE id_mutasi='$id_mutasi'
			       ";
			$q = $this->db->query($sql);

			if($q){				
				$data['result'] = 'true';
				$data['msg'] = 'Success Update Catatan';
			}else{
				$data['result'] = 'false';
				$data['msg'] = 'Failed UPdate Catatan';
			}
				
		}else{
			$data['result'] = 'false';
			$data['msg'] = 'Invalid Token';
		}

		echo json_encode($data);
	}



	public function delete_mutasi(){ 
		$data = array();

		$token  = $this->input->post('token'); 
		$sql = "SELECT * FROM tb_token WHERE token='$token' order by id_token DESC";
		$q = $this->db->query($sql);
		if($q->num_rows() > 0){

			$id_mutasi     = $this->input->post('id_mutasi'); 

			$sql = "DELETE FROM tb_catatan_mutasi
				   WHERE id_mutasi='$id_mutasi'
			       ";
			$q = $this->db->query($sql);

			if($q){				
				$data['result'] = 'true';
				$data['msg'] = 'Success Delete Catatan';
			}else{
				$data['result'] = 'false';
				$data['msg'] = 'Failed Delete Catatan';
			}
				
		}else{
			$data['result'] = 'false';
			$data['msg'] = 'Invalid Token';
		}

		echo json_encode($data);
	}

	public function reset_all_mutasi(){ 
		$data = array();

		$token  = $this->input->post('token'); 
		$id_device = $this->input->post('id_device'); 
		$sql = "SELECT * FROM tb_token WHERE token='$token' order by id_token DESC";
		$q = $this->db->query($sql);
		if($q->num_rows() > 0){

			$sql = "DELETE FROM tb_catatan_mutasi WHERE id_device='$id_device'";
			$q = $this->db->query($sql);

			if($q){				
				$data['result'] = 'true';
				$data['msg'] = 'Success Reset Catatan';
			}else{
				$data['result'] = 'false';
				$data['msg'] = 'Failed Reset Catatan';
			}
				
		}else{
			$data['result'] = 'false';
			$data['msg'] = 'Invalid Token';
		}

		echo json_encode($data);
	}

	public function get_mutasi_in(){ 
		$data = array();

          $id_device = $this->input->post('id_device'); 
		$token  = $this->input->post('token'); 
		$sql = "SELECT * FROM tb_token WHERE token='$token' order by id_token DESC";
		$q = $this->db->query($sql);

		if($q->num_rows() > 0){
			$sql = "SELECT sum(nominal)as total_in FROM tb_catatan_mutasi where id_device='$id_device' AND mutasi='IN' ORDER BY id_mutasi DESC limit 1";
			$q = $this->db->query($sql);
			if($q->num_rows() > 0){				
				$data['result'] = 'true';
				$data['msg']    = 'Total Mutasi IN';
				$data['data']   = $q->result();
			}else{
				$data['result'] = 'false';
				$data['msg']     = 'Tidak ada data';
			}		
		}else{
			$data['result'] = 'false';
			$data['msg']    = 'Invalid Token';	
		}

		echo json_encode($data);
	}

	public function get_mutasi_out(){ 
		$data = array();

          $id_device = $this->input->post('id_device'); 
		$token  = $this->input->post('token'); 
		$sql = "SELECT * FROM tb_token WHERE token='$token' order by id_token DESC";
		$q = $this->db->query($sql);

		if($q->num_rows() > 0){
			$sql = "SELECT sum(nominal)as total_out FROM tb_catatan_mutasi where id_device='$id_device' AND mutasi='OUT' ORDER BY id_mutasi DESC";
			$q = $this->db->query($sql);
			if($q->num_rows() > 0){				
				$data['result'] = 'true';
				$data['msg']    = 'Total Mutasi OUT';
				$data['data']   = $q->result();;
			}else{
				$data['result'] = 'false';
				$data['msg']     = 'Tidak ada data';
			}
		}else{
			$data['result'] = 'false';
			$data['msg']    = 'Invalid Token';	
		}

		echo json_encode($data);
	}

	



}

TESTING API

MENAMBAH TOKEN

method : POST

MELIHAT TOKEN

method : POST

CATAT TOKEN

a2b4f8b4f61c2729ae95b57b122bf6029a90212f598f872450c915884e4e1fc163f555c1bd0c4e861dfe1510124da6525a533aa667a652cf7b08050d35f0ee65

MENAMBAH KATEGORI

method : POST

MELIHAT KATEGORI

method : POST

MENAMBAH MUTASI

method : POST

MELIHAT MUTASI

method : POST

MELIHAT MUTASI IN

method : POST

MELIHAT MUTASI OUT

method : POST

UPDATE MUTASI

method : POST

DELETE MUTASI

method : POST

RESET MUTASI

method : POST

FLUTTER

1. Buat Project dengan nama : catatanku

2. Tambahkan Package pada pubspec.yaml

  dio: ^3.0.7
  nice_button: ^0.1.7
  sweetalert: ^0.0.1
  unique_id: ^0.0.2
  fancy_bottom_navigation: ^0.3.2

3. Tambahkan pada Folder Lib

4. ubah main.dart

import 'package:flutter/material.dart';
import './ui/screen/home.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(new MaterialApp(
    debugShowCheckedModeBanner: false,
    title: "CATATANKU",
    theme: ThemeData(brightness: Brightness.light, primaryColor: Colors.blue),
    home: new Home(),
  ));
}
//BARIS 11
//import 'package:catatanku/main.dart';


//BARIS 16
//await tester.pumpWidget(MyApp());

5. Comment baris 11& 16 pada File test/widget_test.dart

6. buat file Lib/ui/screen/home.dart

import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import 'package:nice_button/nice_button.dart';
import 'package:sweetalert/sweetalert.dart';
import 'package:unique_id/unique_id.dart';
import 'package:fancy_bottom_navigation/fancy_bottom_navigation.dart';
import 'addMutasi.dart';

class Home extends StatefulWidget {
  Home({Key key}) : super(key: key);

  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {

  String device_id;


  @override
  void initState() {
    super.initState();
    getId();
  }

  Future getId()async{
      setState(() async {
        device_id = await UniqueId.getID;
      }); 
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      bottomNavigationBar: FancyBottomNavigation(
        tabs: [
          TabData(iconData: Icons.home, title: "Home"),
          TabData(iconData: Icons.add, title: "ADD"),
          TabData(iconData: Icons.file_upload, title: "IN"),
          TabData(iconData: Icons.file_download, title: "OUT")
        ],
        onTabChangedListener: (position) {
          if(position==1){
              Navigator.push(context, new MaterialPageRoute(
                  builder: (BuildContext context) => new addMutasi(),
              ));
          }
        },
      ),
      body: SafeArea(
        child: Container(
          child: SingleChildScrollView(
            child: Column(
              children: <Widget>[
                Stack(
                  children: <Widget>[backgroundHeader(), summaryCash()],
                ),

                Text(device_id.toString()),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

Widget backgroundHeader() {
  return Container(
    height: 250,
    width: double.infinity,
    decoration: BoxDecoration(
      color: Colors.blueAccent,
      borderRadius: BorderRadius.only(
        bottomLeft: Radius.circular(30),
        bottomRight: Radius.circular(30),
      ),
    ),
    child: Padding(
      padding: const EdgeInsets.only(top: 60, left: 20),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Text(
            "CATATAN KEUANGAN HARIAN",
            style: TextStyle(
                fontSize: 20, color: Colors.white, fontWeight: FontWeight.bold),
          ),
          Text(
            "ID",
            style: TextStyle(
              fontSize: 15,
              color: Colors.white,
            ),
          ),
        ],
      ),
    ),
  );
}

Widget summaryCash() {
  return Positioned(
    top: 150,
    left: 20,
    child: Container(
      width: 350,
      height: 140,
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(30),
      ),
      child: Padding(
        padding: const EdgeInsets.only(top: 30.0),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Column(
              children: <Widget>[
                Text("Penghasilan"),
                Divider(),
                Text(
                  "15.000 K",
                  style: TextStyle(fontSize: 25, fontWeight: FontWeight.bold),
                ),
              ],
            ),
            Column(
              children: <Widget>[
                Text("Pengeluaran"),
                Divider(),
                Text(
                  "3.250 K",
                  style: TextStyle(fontSize: 25, fontWeight: FontWeight.bold),
                ),
              ],
            ),
          ],
        ),
      ),
    ),
  );
}

Widget cardDetail(title, description, price, type) {
  return Card(
    margin: EdgeInsets.only(top: 15, left: 15, right: 15),
    elevation: 8,
    child: ListTile(
      leading: Icon(
        type == 'out'
            ? Icons.subdirectory_arrow_left
            : Icons.subdirectory_arrow_right,
        color: type == 'out' ? Colors.redAccent : Colors.lightGreen,
      ),
      title: Text(
        title,
        style: TextStyle(fontWeight: FontWeight.bold),
      ),
      subtitle: Text(description),
      trailing: Text(
        "Rp " + price,
        style: TextStyle(
            color: type == 'out' ? Colors.redAccent : Colors.lightGreen),
      ),
    ),
  );
}

addMutasi.dart

import 'package:flutter/material.dart';
import 'package:sweetalert/sweetalert.dart';
import 'package:nice_button/nice_button.dart';
import 'package:dio/dio.dart';
import 'package:unique_id/unique_id.dart';
import 'package:catatanku/core/config/dioConfig.dart';
import 'home.dart';


class addMutasi extends StatefulWidget {
  @override
  _addMutasiState createState() => _addMutasiState();
}

class _addMutasiState extends State<addMutasi> {
  String _title = "ADD MUTASI";

  final TextEditingController _judul = new TextEditingController();
  final TextEditingController _deskripsi = new TextEditingController();
  String _cbMutasi;
  String device_id;


  @override
  void initState() { 
    super.initState();
    getId();
    _cbMutasi = "IN";
  }

  Future getId()async{
      setState(() async {
        device_id = await UniqueId.getID;
        _title = device_id;
      }); 
  }

  void addMutasi() async {
    try {

      if(_judul.text=="" || _deskripsi.text==""){
        SweetAlert.show(context,subtitle: "Empty Field", style: SweetAlertStyle.error);
      }else{

          SweetAlert.show(context,subtitle: "Saving Mutasi", style: SweetAlertStyle.loading);
          new Future.delayed(new Duration(seconds: 2),()async{

              FormData formData = new FormData.fromMap({
                "token": dioConfig.apiToken,
                'id_device': device_id,
                'id_kategori': "1",
                'mutasi': _cbMutasi,
                'judul': _judul.text.toString(),
                'deskripsi': _deskripsi.text.toString(),
                'nominal': 50000,
                'tgl': "2019-12-13"
              });

              Dio dio = new Dio(dioConfig.options);
              Response response = await dio.post(dioConfig.baseUrl+"add_mutasi", data: formData);
              print(response);
              // SweetAlert.show(context,subtitle: "Save Success", style: SweetAlertStyle.error);

              Navigator.push(context, new MaterialPageRoute(
                  builder: (BuildContext context) => new Home(),
              ));

          });


      }

    } catch (e) {
      print(e);
    }

  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(_title),
        ),
        body: _layout(context),
      );
  }

  Widget _layout(BuildContext context) {
    return SafeArea(
      child: Container(
        child: Center(
          child: SingleChildScrollView(
            child: Column(
              children: <Widget>[

                Container(
                  margin: EdgeInsets.all(5),
                  padding: EdgeInsets.all(10),
                  child: new TextField(
                    controller: _judul,
                    decoration: new InputDecoration(labelText: 'Judul'),
                  ),
                ),

                Container(
                  margin: EdgeInsets.all(5),
                  padding: EdgeInsets.all(10),
                  child: new TextField(
                    controller: _deskripsi,
                    decoration: new InputDecoration(labelText: 'Deskripsi'),
                    keyboardType: TextInputType.text,
                  ),
                ),

                Container(
                  margin: EdgeInsets.all(5),
                  padding: EdgeInsets.all(10),
                  child: DropdownButtonFormField<String>(
                    value: _cbMutasi,
                    items: ["IN", "OUT"]
                        .map((label) => DropdownMenuItem(
                              child: Text(label),
                              value: label,
                            ))
                        .toList(),
                    onChanged: (value) {
                      setState(() => _cbMutasi = value);
                    },
                  ),
                ),
                
                SizedBox(height: 30),

                NiceButton(
                    radius: 40,
                    padding: const EdgeInsets.all(15),
                    text: "Save Data",
                    icon: Icons.refresh,
                    background: Colors.blue,
                    gradientColors: [Color(0xff5b86e5), Color(0xff36d1dc)],
                    onPressed: () {
                      addMutasi();
                    }),
                SizedBox(height: 30),
   

              ],
            ),
          ),
        ),
      ),
    );
  }
}

Coming Soon

Coding Talk #02 : FLUTTER CRUD API WITH DIO & PHP

By Maulana Ilham

Coding Talk #02 : FLUTTER CRUD API WITH DIO & PHP

FLUTTER CRUD API WITH DIO & PHP

  • 1,890