Flutter Dasar

Pertemuan #5

Toko Kopi Haqiqi Cilebut, 03 Agustus 2019

oleh : k4ilham & LT

MYSQL

TABLE KARYAWAN

CREATE TABLE `karyawan` (
  `karId` int(11) NOT NULL,
  `karNik` char(4) DEFAULT NULL,
  `karNama` varchar(40) DEFAULT NULL,
  `karGol` char(2) DEFAULT NULL,
  `karStatus` char(1) DEFAULT NULL,
  `karHp` char(15) DEFAULT NULL,
  `karEmail` varchar(40) DEFAULT NULL,
  `karAlamat` text,
  `karFoto` varchar(100) DEFAULT NULL,
  `createdAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `updatedAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `createdUser` char(5) DEFAULT NULL,
  `updatedUser` char(5) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

TABLE USER

CREATE TABLE `user` (
  `userId` int(11) NOT NULL,
  `userNik` char(4) DEFAULT NULL,
  `userName` varchar(40) DEFAULT NULL,
  `userPass` varchar(40) DEFAULT NULL,
  `userLevel` char(1) DEFAULT NULL,
  `userStatus` char(1) DEFAULT NULL,
  `userToken` varchar(200) DEFAULT NULL,
  `createdAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `updatedAt` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  `createdUser` char(5) DEFAULT NULL,
  `updatedUser` char(5) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

VIEW KARYAWAN

CREATE VIEW viewKaryawan AS
SELECT
a.karId,a.karNik,a.karNama,a.karGol,a.karStatus, a.karHp,a.karEmail,a.karAlamat,a.karFoto,
b.userId,b.userName,b.userPass,b.userLevel,b.userStatus,b.userToken
FROM karyawan AS a 
INNER JOIN user AS b 
ON a.karNik = b.userNik

Trigger AddUser


  INSERT INTO user(
      userNik, userName, userPass, userLevel, userStatus
  )VALUES(      
      OLD.karNik,
      OLD.karNik,
      md5('12345678'),
      '0'
  );
UPDATE user SET userStatus = '0' WHERE NEW.karStatus = 'O'

Trigger UpdateStatusUser

Framework CI

config : database

	'hostname' => 'localhost',
	'username' => 'username kamu',
	'password' => 'password kamu',
	'database' => 'nama database',
	'dbdriver' => 'mysqli',

model : M_Karyawan

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class M_Karyawan extends CI_Model {

	 function getKaryawan($nik= null){
	 	if($nik===null){
			 //ALL KARYAWAN
	 		return $this->db->get('viewKaryawan')->result_array();
	 	}else{
			 //DETAIL KARYAWAN
	 		return $this->db->get_where('viewKaryawan',['karNik' => $nik])->result_array();
	 	}
	 }


	 function getKaryawanByName($kriteria= null){
		if($kriteria===null){
			//ALL KARYAWAN
	 		return $this->db->get('viewKaryawan')->result_array();
	 	}else{
			//FILTER KARYAWAN
			$this->db->like('karNik',$kriteria);
			$this->db->or_like('karNama',$kriteria);
			return $query = $this->db->get('viewKaryawan')->result_array();	
	 	}

	 }	

}

CONTROLLER : Karyawan

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
require APPPATH . '/libraries/REST_Controller.php';
require APPPATH . '/libraries/php-jwt-master/src/JWT.php';

use \Firebase\JWT\JWT;
use Restserver\Libraries\REST_Controller;

class Karyawan extends REST_Controller {
    
	//INIT
   function __construct() {
        parent::__construct();
        $this->load->database();
        $this->load->model('M_Karyawan');
   }


    //GET
   public function index_get(){	   

        //TOKEN JWT
        $key = "meetApFlutterMobileTokoKopiHaqiqiCilebut";
        $web = array( "web" => "http://kailham.com",);
        //ENCODE TOKEN
        $jwt = JWT::encode($web, $key);
        //DECODE TOKEN
        $decoded = JWT::decode($jwt, $key, array('HS256'));

	//GET PARAMETER
	$kriteria = $this->get('kriteria');
        $token    = $this->get('token');
        $data     = "";

	//METHOD
	if($kriteria===null){
           //ALL KARYAWAN
	   $data = $this->M_Karyawan->getKaryawan();
	}else{
           //FILTER BY NIK & NAME
	   $data = $this->M_Karyawan->getKaryawanByName($kriteria);
	}


	   //TOKEN MATCH
        if($jwt==$token){
                //DATA FOUND
                if($data)
                {
                        $this->response([
                                        'status' => True,
                                        'message' => 'Karyawan found',
                                        'token' => $jwt,
                                        'data' => $data,
                                ], REST_Controller::HTTP_OK); 
	
                //DATA NOT FOUND
                }else{
                    $this->response([
                            'status' => False,
                            'message' => 'Karyawan not found',
                        ], REST_Controller::HTTP_NOT_FOUND); 
                }
        }else{
		     //INVALID TOKEN
                    $this->response([
                            'status' => False,
                            'message' => 'Invalid Token',
                            'token' => $jwt,
                        ], REST_Controller::HTTP_NOT_FOUND);
        }
   }
	


	
}

http://kailham.com/apiSikar/karyawan?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ3ZWIiOiJodHRwOlwvXC9rYWlsaGFtLmNvbSJ9.cGCF3rTk2yvcvL9JYLgQpeONXDRYq5iC0Hj56ENCnI8&kriteria=

POSTMAN

Json 2 Dart

Text

PUBSPEC

name: SIKAR
description: Sistem Informasi Karyawan.


version: 1.0.0+1

environment:
  sdk: ">=2.1.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter


  cupertino_icons: ^0.1.2
  url_launcher: ^4.0.3
  shared_preferences: ^0.4.2
  flutter_money_formatter: ^0.8.2
  http: 0.12.0+2
  flutter_html: ^0.8.2

dev_dependencies:
  flutter_test:
    sdk: flutter


flutter:

  uses-material-design: true

  assets:
    - assets/images/
    - assets/data/

CONFIG

import 'package:flutter/material.dart';
import 'package:flutter_money_formatter/flutter_money_formatter.dart';

class strings {
  //STRING
  static const String app_name = "SIKAR 1.0";
  static const String app_title = "PT. meetAp Mobile Developer";

  static const base_url = 'http://kailham.com/apiSikar/';
  static const token =
      'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ3ZWIiOiJodHRwOlwvXC9rYWlsaGFtLmNvbSJ9.cGCF3rTk2yvcvL9JYLgQpeONXDRYq5iC0Hj56ENCnI8';
  static const imageUrl = 'http://kailham.com/apiSikar/images/karyawan/';
  static const imageUrlEmpty =
      'https://lejeunefoundation.org/wp-content/uploads/2017/06/male.jpg';

  static const String text_home = "Home";
  static const String text_attendance = "Attendance";
  static const String text_profile = "Profile";
  static const String text_profil = "Profile";
  static const String text_sallary = "Sallary";
  static const String text_login = "Login";
  static const String text_login_hint = "Pin Code";
}

class sizes{
  //SIZE
  static const bigRadius = 66.0;
  static const buttonHeight = 24.0;
}

class pages{
  //PAGES
  static const loginPageTag = 'LoginPage';
  static const homePageTag = 'HomePage';
}

class colors {
  //COLOR
  static const ColorPrimaryDark = Color.fromRGBO(58, 66, 86, 1.0);
  //static const ColorPrimary = Color.fromRGBO(64, 75, 96, .9);

//  static const Color ColorPrimaryDark= Colors.red;
  static const Color ColorPrimary = Colors.green;

  static const Color ColorTeks = Colors.white;
  static const Color ColorTeksError = Colors.red;
  static const Color ColorButton = Colors.green;
  static const Color ColorButtonGradient = Colors.greenAccent;
  static const Color ColorIcon = Colors.white;
}

class icons {
  //ICON
  static const IconData icon_app = Icons.android;
  static const IconData icon_home = Icons.home;
  static const IconData icon_attendance = Icons.timelapse;
  static const IconData icon_sallary = Icons.monetization_on;
  static const IconData icon_profile = Icons.people_outline;
  static const IconData icon_back = Icons.arrow_back;
  static const IconData icon_login_email = Icons.alternate_email;
  static const IconData icon_login_password = Icons.lock;
}

class images {
  //IMAGE
  static const String img_logo = "assets/images/logo.jpg";
  static const String img_header = "assets/images/header.jpg";
  static const String img_profil = "assets/images/profil.jpg";

  static const String img_attendance_hadir = "assets/images/icon_hadir.png";
  static const String img_attendance_libur = "assets/images/icon_libur.png";
  static const String img_attendance_cuti = "assets/images/icon_cuti.png";
  static const String img_attendance_ijin = "assets/images/icon_ijin.png";
  static const String img__attendance_alpa = "assets/images/icon_alpa.png";

  static const String img_bulan1 = "assets/images/m1.jpg";
  static const String img_bulan2 = "assets/images/m2.jpg";
  static const String img_bulan3 = "assets/images/m3.jpg";
  static const String img_bulan4 = "assets/images/m4.jpg";
  static const String img_bulan5 = "assets/images/m5.jpg";
  static const String img_bulan6 = "assets/images/m6.jpg";
  static const String img_bulan7 = "assets/images/m7.jpg";
  static const String img_bulan8 = "assets/images/m8.jpg";
  static const String img_bulan9 = "assets/images/m9.jpg";
  static const String img_bulan10 = "assets/images/m10.jpg";
  static const String img_bulan11 = "assets/images/m11.jpg";
  static const String img_bulan12 = "assets/images/m12.jpg";
}

class datas{

  static const List<String> data_absen_tgl =[
    '11 Jun 2019',
    '12 Jun 2019',
    '13 Jun 2019',
    '14 Jun 2019',
    '15 Jun 2019',
    '16 Jun 2019',
    '17 Jun 2019',
    '18 Jun 2019',
    '19 Jun 2019',
    '20 Jun 2019',
    '21 Jun 2019',
    '22 Jun 2019',
    '23 Jun 2019',
    '24 Jun 2019',
    '25 Jun 2019',
    '26 Jun 2019',
    '27 Jun 2019',
    '28 Jun 2019',
    '29 Jun 2019',
    '30 Jun 2019',
  ];

  static const List<String> data_absen_status = [
    '1',
    '1',
    '0',
    '1',
    '2',
    '2',
    '3',
    '3',
    '1',
    '1',
    '1',
    '2',
    '2',
    '1',
    '1',
    '4',
    '0',
    '1',
    '2',
    '2',
  ];

}

class absen{
  static String findAbsenStatus(String value){
    String result;

    if(value=='1'){
      result = "Hadir";
    }else if(value=='2'){
      result = "Libur";
    }else if(value=='3'){
      result = "Cuti";
    }else if(value=='4'){
      result = "Ijin";
    }else if(value=='0'){
      result = "Alpa";
    }

    return result;
  }

  static String findAbsenIcon(String value){
    String result;

    if(value=='1'){
      result = images.img_attendance_hadir;
    }else if(value=='2'){
      result = images.img_attendance_libur;
    }else if(value=='3'){
      result = images.img_attendance_cuti;
    }else if(value=='4'){
      result = images.img_attendance_ijin;
    }else if(value=='0'){
      result = images.img__attendance_alpa;
    }

    return result;
  }



  static String findMonthIcon(String value){
    String result;

    if(value=='1'){
      result = images.img_bulan1;
    }else if(value=='2'){
      result = images.img_bulan2;
    }else if(value=='3'){
      result = images.img_bulan3;
    }else if(value=='4'){
      result = images.img_bulan4;
    }else if(value=='5'){
      result = images.img_bulan5;
    }else if(value=='6'){
      result = images.img_bulan6;
    }else if(value=='7'){
      result = images.img_bulan7;
    }else if(value=='8'){
      result = images.img_bulan8;
    }else if(value=='9'){
      result = images.img_bulan9;
    }else if(value=='10'){
      result = images.img_bulan10;
    }else if(value=='11'){
      result = images.img_bulan11;
    }else if(value=='12'){
      result = images.img_bulan12;
    }

    return result;
  }


}


UrlLaucher

import 'package:url_launcher/url_launcher.dart';

class URLLauncher {

  launchURL(String url) async {
    if (await canLaunch(url)) {
      await launch(url);
    } else {
      throw 'Could not launch $url';
    }
  }

}

newEmp

import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
import '../helper/URLLauncher.dart';
import '../helper/config.dart' as appConfig;

class newEmp extends StatefulWidget {
  newEmpState createState() => newEmpState();
}
class newEmpState extends State<newEmp> {
  //VARIABEL
  List data;
  String kriteria = '';

  //GET DATA
  Future<String> getKaryawan(String kriteria) async {
    String method = 'karyawan';
    String url =
        appConfig.strings.base_url + method + '?token=' + appConfig.strings.token + "&kriteria=" + kriteria;
    var res = await http
        .get(Uri.encodeFull(url), headers: {'accept': 'application/json'});
    setState(() {
      var content = json.decode(res.body);
      data = content['data'];
    });
    return 'success!';
  }

  //INIT
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    this.getKaryawan('');
  }

  Widget build(context) {
    return MaterialApp(
        color: appConfig.colors.ColorPrimaryDark,
        debugShowCheckedModeBanner: false,
        home: Scaffold(
          backgroundColor: appConfig.colors.ColorPrimaryDark,

          //HEADER
          appBar: AppBar(
            backgroundColor: appConfig.colors.ColorPrimaryDark,

            //SEARCH BAR
            title: TextField(
              decoration: InputDecoration(
                fillColor: Colors.white,
                hoverColor: Colors.green,
                focusColor: Colors.yellow,
                icon: Icon(
                  Icons.search,
                  color: Colors.white,
                ),
                hintText: 'Search here',
                hintStyle: TextStyle(
                  color: Colors.white,
                ),
              ),
              //ACTION ON CHANGE
              onChanged: (String value) {
                setState(() {
                  kriteria = value;
                  this.getKaryawan(kriteria);
                });
              },
            ),
          ),

          //CONTENT
          body: dataList(context),
        ));
  }

  Widget dataList(BuildContext context) {
    return Container(
      decoration: BoxDecoration(color: appConfig.colors.ColorPrimaryDark),
      margin: EdgeInsets.all(10.0),

      //LIST VIEW
      child: ListView.builder(
        itemCount: data == null ? 0 : data.length,
        itemBuilder: (BuildContext context, int index) {

          //VARIABEL
          String alamatImage = "";
          data[index]['karFoto'] != "" ? alamatImage = appConfig.strings.imageUrl + data[index]['karFoto'] : alamatImage = appConfig.strings.imageUrlEmpty;
          final String alamatWA = 'https://api.whatsapp.com/send?phone='+ data[index]['karHp'] +'&text=Halo%20' + data[index]['karNama'];

          return Container(
              decoration:
                  BoxDecoration(color: appConfig.colors.ColorPrimaryDark),

              //CARD
              child: Card(
                color: appConfig.colors.ColorPrimary,
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: <Widget>[

                    //LIST TILE
                    ListTile(
                      contentPadding: EdgeInsets.symmetric(
                          horizontal: 20.0, vertical: 10.0),

                      //ACTIONS ON TAP
                      onTap: () {
                        URLLauncher().launchURL(alamatWA);
                      },

                      //FOTO
                      leading: Container(
                          padding: EdgeInsets.only(right: 12.0),
                          decoration: new BoxDecoration(
                              border: new Border(
                                  right: new BorderSide(
                                      width: 1.0, color: Colors.white24))),
                          child: Hero(
                            tag: "avatar_" + data[index]['karNama'],
                            child: CircleAvatar(
                              radius: 32,
                              backgroundImage: NetworkImage(alamatImage),
                            ),
                          )),

                      //NAMA
                      title: Text(
                        data[index]['karNama'],
                        style: TextStyle(
                            fontSize: 15.0,
                            fontWeight: FontWeight.bold,
                            color: appConfig.colors.ColorTeks),
                      ),

                      //ICON CHAT
                      trailing: Icon(Icons.chat,
                          color: Colors.white, size: 30.0),

                      //SUBTITLE
                      subtitle: Column(
                        children: <Widget>[

                          //NIK
                          Row(
                            children: <Widget>[
                              Text(
                                'NIK : ',
                                style: TextStyle(
                                    fontWeight: FontWeight.bold,
                                    color: appConfig.colors.ColorTeks),
                              ),
                              Text(
                                data[index]['karNik'].toString().isNotEmpty
                                    ? data[index]['karNik']
                                    : '-',
                                style: TextStyle(
                                    fontStyle: FontStyle.italic,
                                    fontSize: 15.0,
                                    color: appConfig.colors.ColorTeks),
                              ),
                            ],
                          ),

                          //HP
                          Row(
                            children: <Widget>[
                              Text(
                                'HP : ',
                                style: TextStyle(
                                    fontWeight: FontWeight.bold,
                                    color: appConfig.colors.ColorTeks),
                              ),
                              Text(
                                data[index]['karHp'] != null
                                    ? data[index]['karHp']
                                    : '-',
                                style: TextStyle(
                                    color: appConfig.colors.ColorTeks),
                              ),
                            ],
                          ),



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

preview

meetap_flutter_basic_05

By Maulana Ilham

meetap_flutter_basic_05

meetap_flutter_basic_05

  • 823