Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // const route
- class Constant {
- static const String baseUrl = "http://192.168.6.106/latihan/api/";
- static const String apiAddProduct = baseUrl + "addproduct.php";
- static const String apiGetProduct = baseUrl + "getproduct.php";
- static const String apiLogin = baseUrl + "login.php";
- }
- // entry dart
- import 'package:flutter/material.dart';
- import 'package:flutter_cupertino_date_picker/flutter_cupertino_date_picker.dart';
- import 'package:barcode_scan/barcode_scan.dart';
- import 'package:flutter/services.dart';
- import 'dart:async';
- import 'dart:convert';
- import 'package:http/http.dart' as http;
- import 'const.dart';
- class Response {
- final String status;
- final String message;
- Response({this.status, this.message});
- factory Response.fromJson(Map<String, dynamic> json) {
- return Response(
- status: json['status'],
- message: json['message'],
- );
- }
- }
- Future<Response> post(String url,var body)async{
- return await http
- .post(Uri.encodeFull(url), body: body, headers: {"Accept":"application/json"})
- .then((http.Response response) {
- final int statusCode = response.statusCode;
- if (statusCode < 200 || statusCode > 400 || json == null) {
- throw new Exception("Error while fetching data");
- }
- return Response.fromJson(json.decode(response.body));
- });
- }
- class EntryData extends StatefulWidget {
- @override
- EntryDataState createState() => new EntryDataState();
- }
- class EntryDataState extends State<EntryData> {
- // text field
- final _nomerRakController = TextEditingController();
- final _namaProdukController = TextEditingController();
- // dropdown category
- List _category = ["Buah-buahan", "Snack", "Stationary", "Baju", "Ice Cream"];
- List<DropdownMenuItem<String>> _dropDownMenuItems;
- String _currentCategory;
- // datepicker
- String _datetime = '';
- int _year = 2018;
- int _month = 11;
- int _date = 11;
- // radio
- String _radioValue1;
- // scanner
- String _scanResult = '';
- // member simpan data
- String _response = '';
- bool apiCall = false;
- @override
- void initState() {
- super.initState();
- // dropdown category
- _dropDownMenuItems = getDropDownMenuItems();
- _currentCategory = _dropDownMenuItems[0].value;
- // datepicker
- DateTime now = DateTime.now();
- _year = now.year;
- _month = now.month;
- _date = now.day;
- }
- // widget simpan data
- Widget getProperWidget(){
- if(apiCall)
- return AlertDialog(
- content: new Column(
- children: <Widget>[
- CircularProgressIndicator(),
- Text("Please wait")
- ],
- )
- );
- else
- return Center(
- child: Text(
- _response,
- style: new TextStyle(fontSize: 15.0)
- )
- );
- }
- void _callPostAPI() {
- post(
- Constant.apiAddProduct,
- {
- "nomor_rak": _nomerRakController.text,
- "nama_produk": _namaProdukController.text,
- "kategori": _currentCategory,
- "expired_date": _datetime,
- "scan_code": _scanResult,
- "discount": _radioValue1
- }).then((response) {
- setState(() {
- apiCall = false;
- _response = response.message;
- });
- // tambahkan baris ini
- Navigator.pop(context);
- },
- onError: (error) {
- apiCall = false;
- _response = error.toString();
- }
- );
- }
- // dropdown category
- List<DropdownMenuItem<String>> getDropDownMenuItems() {
- List<DropdownMenuItem<String>> items = new List();
- for (String kategori in _category) {
- items.add(new DropdownMenuItem(
- value: kategori,
- child: new Text(kategori)
- ));
- }
- return items;
- }
- void changedDropDownItem(String selectedCategory) {
- setState(() {
- _currentCategory = selectedCategory;
- });
- }
- // radio discount
- void _handleRadioValueChange1(String value) {
- setState(() {
- _radioValue1 = value;
- });
- }
- /// Display date picker.
- void _showDatePicker() {
- final bool showTitleActions = false;
- DatePicker.showDatePicker(
- context,
- showTitleActions: true,
- minYear: 2019,
- maxYear: 2022,
- initialYear: _year,
- initialMonth: _month,
- initialDate: _date,
- confirm: Text(
- 'PILIH',
- style: TextStyle(color: Colors.red),
- ),
- cancel: Text(
- 'BATAL',
- style: TextStyle(color: Colors.cyan),
- ),
- locale: "en",
- dateFormat: "dd-mm-yyyy",
- onChanged: (year, month, date) {
- //debugPrint('onChanged date: $year-$month-$date');
- if (!showTitleActions) {
- _changeDatetime(year, month, date);
- }
- },
- onConfirm: (year, month, date) {
- _changeDatetime(year, month, date);
- },
- );
- }
- void _changeDatetime(int year, int month, int date) {
- setState(() {
- _year = year;
- _month = month;
- _date = date;
- _datetime = '$date-$month-$year';
- });
- }
- // scan QR
- Future _scanQR() async {
- try {
- String qrResult = await BarcodeScanner.scan();
- setState(() {
- _scanResult = qrResult;
- });
- } on PlatformException catch (ex) {
- if (ex.code == BarcodeScanner.CameraAccessDenied) {
- setState(() {
- _scanResult = "Camera permission was denied";
- });
- } else {
- setState(() {
- _scanResult = "Unknown Error $ex";
- });
- }
- } on FormatException {
- setState(() {
- _scanResult = "You pressed the back button before scanning anything";
- });
- } catch (ex) {
- setState(() {
- _scanResult = "Unknown Error $ex";
- });
- }
- }
- @override
- Widget build(BuildContext context) {
- return Scaffold(
- appBar: AppBar(
- title: Text('Produk Entry'),
- ),
- body: SafeArea(
- child: ListView(
- padding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),
- children: <Widget>[
- // text field
- TextField(
- controller: _nomerRakController,
- decoration: InputDecoration(
- filled: false,
- labelText: 'Nomer Rak',
- ),
- ),
- // spacer
- SizedBox(height: 5.0),
- // text field
- TextField(
- controller: _namaProdukController,
- decoration: InputDecoration(
- filled: false,
- labelText: 'Nama Produk',
- ),
- ),
- // Dropdown
- new Container(
- padding: EdgeInsets.all(10.0),
- //color: Colors.blueGrey,
- child: new Row(
- children: <Widget>[
- new Text("Kategori: ", style: new TextStyle(fontSize: 15.0)),
- new DropdownButton(
- value: _currentCategory,
- items: _dropDownMenuItems,
- onChanged: changedDropDownItem,
- )
- ],
- ),
- ),
- // datepicker
- new Container(
- //padding: EdgeInsets.all(10.0),
- //color: Colors.blueGrey,
- child: new Row(
- children: <Widget>[
- RaisedButton(
- child: Text('Expired Date', style: new TextStyle(fontSize: 15.0)),
- onPressed: () {
- _showDatePicker();
- },
- ),
- new Text(" $_datetime", style: new TextStyle(fontSize: 15.0)),
- ],
- ),
- ),
- // QR scanner
- new Container(
- //padding: EdgeInsets.all(10.0),
- //color: Colors.blueGrey,
- child: new Row(
- children: <Widget>[
- RaisedButton(
- child: Text(' Scan Code ', style: new TextStyle(fontSize: 15.0)),
- onPressed: () {
- _scanQR();
- },
- ),
- new Text(" $_scanResult", style: new TextStyle(fontSize: 15.0)),
- ],
- ),
- ),
- // Radio
- new Container(
- //padding: EdgeInsets.all(10.0),
- //color: Colors.blueGrey,
- child: new Row(
- children: <Widget>[
- new Radio(
- value: "Discount",
- groupValue: _radioValue1,
- onChanged: _handleRadioValueChange1,
- ),
- new Text(
- 'Discount',
- style: new TextStyle(fontSize: 15.0),
- ),
- new Radio(
- value: "Non Discount",
- groupValue: _radioValue1,
- onChanged: _handleRadioValueChange1,
- ),
- new Text(
- 'Non Discount',
- style: new TextStyle(fontSize: 15.0),
- ),
- ],
- ),
- ),
- // button
- RaisedButton(
- child: Text('SIMPAN'),
- onPressed: () {
- setState((){
- apiCall=true; // Set state like this
- });
- _callPostAPI();
- },
- ),
- // POST Response
- getProperWidget(),
- ],
- )
- ),
- );
- }
- }
- // list.dart
- import 'package:flutter/material.dart';
- import 'package:flutter_app/login.dart';
- import 'dart:convert';
- import 'dart:async';
- import 'package:http/http.dart' as http;
- import 'package:flutter/foundation.dart';
- import 'package:shared_preferences/shared_preferences.dart';
- import 'const.dart';
- // class untuk objek json
- class Product {
- final String id;
- final String nama_produk;
- final String kategori;
- final String expired_date;
- final String nomor_rak;
- final String scan_code;
- final String discount;
- Product({this.id, this.nama_produk, this.kategori, this.expired_date,
- this.nomor_rak, this.scan_code, this.discount});
- factory Product.fromJson(Map<String, dynamic> json) {
- return Product(
- id: json['id'] as String,
- nama_produk: json['nama_produk'] as String,
- kategori: json['kategori'] as String,
- expired_date: json['expired_date'] as String,
- nomor_rak: json['nomor_rak'] as String,
- scan_code: json['scan_code'] as String,
- discount: json['discount'] as String,
- );
- }
- }
- // fungsi parse foto untuk mengubah dari string json ke array List<Photo>
- List<Product> parseProduct(String responseBody) {
- final parsed = json.decode(responseBody).cast<Map<String,dynamic>>();
- return parsed.map<Product>((json)=>Product.fromJson(json)).toList();
- }
- // fungsi fetch untuk mengubah dari end point api ke array List<Photo>
- Future<List<Product>> fetchProduct(http.Client client) async {
- final response = await client.get(Constant.apiGetProduct);
- return compute(parseProduct, response.body);
- }
- class ProductList extends StatelessWidget {
- @override
- Widget build(BuildContext context) {
- return FutureBuilder <List<Product>> (
- future: fetchProduct(http.Client()),
- builder: (context, snapshot) {
- if (snapshot.hasError) print(snapshot.error);
- return (snapshot.hasData) ? ProductListBuilder(photos: snapshot.data):
- Center(child: CircularProgressIndicator());
- }
- );
- }
- }
- class ProductListBuilder extends StatelessWidget {
- final List<Product> photos;
- ProductListBuilder({Key key, this.photos}) : super(key : key);
- @override
- Widget build(BuildContext context) {
- return ListView.builder(
- itemCount: photos.length,
- itemBuilder: (context, index) {
- return ListTile (
- // title: Text('Title '+photos[index].title),
- title : Column (
- children: <Widget>[
- ListTile(
- title: Text("Nama Produk : ${photos[index].nama_produk}"),
- subtitle: Text(
- "Kategori : ${photos[index].kategori} \n"+
- "Expired date : ${photos[index].expired_date} \n" +
- "Nomor Rak : ${photos[index].nomor_rak} \n" +
- "Scan code : ${photos[index].scan_code} \n" +
- "Diskon : ${photos[index].discount} \n"
- ),
- ),
- Divider(),
- ],
- ),
- );
- },
- );
- }
- }
- Widget listProduct (BuildContext context) {
- return new Scaffold(
- appBar: new AppBar(
- title: const Text("W2 Flutter"),
- ),
- body: new ProductList(),
- floatingActionButton: FloatingActionButton(
- child: Icon(Icons.add),
- onPressed: () {
- Navigator.pushNamed(context, '/entry');
- }
- ),
- drawer: Drawer(
- child: ListView(
- children: <Widget>[
- UserAccountsDrawerHeader(
- accountName: Text("Wisnu Wijokangko"),
- accountEmail: Text("wisnuwijo3@gmail.com"),
- decoration: BoxDecoration(
- color: Colors.blueAccent,
- ),
- currentAccountPicture:
- CircleAvatar(
- backgroundImage: NetworkImage("https://i0.wp.com/www.winhelponline.com/blog/wp-content/uploads/2017/12/user.png?fit=256%2C256&quality=100&ssl=1"),
- ),
- ),
- ListTile(
- title: Text('Profile'),
- trailing: Icon(Icons.person),
- leading: Icon(Icons.arrow_right),
- onTap: () {
- },
- ),
- ListTile(
- title: Text('Favorites'),
- trailing: Icon(Icons.favorite),
- leading: Icon(Icons.arrow_right),
- onTap: () {
- },
- ),
- ListTile(
- title: Text('Settings'),
- trailing: Icon(Icons.settings),
- leading: Icon(Icons.arrow_right),
- onTap: () {
- },
- ),
- ListTile(
- title: Text('Logout'),
- trailing: Icon(Icons.exit_to_app),
- leading: Icon(Icons.arrow_right),
- onTap: () async {
- // redirect ke login
- Navigator.pop(context);
- Navigator.push(
- context,
- MaterialPageRoute(builder: (context) => Login())
- );
- Navigator.of(context).pushNamedAndRemoveUntil('/login',
- (Route<dynamic> route) => false);
- final prefs = await SharedPreferences.getInstance();
- prefs.remove('login');
- },
- ),
- ],
- ),
- ),
- );
- }
- // login
- import 'package:flutter/material.dart';
- import 'dart:async';
- import 'dart:convert';
- import 'package:http/http.dart' as http;
- import 'package:flutter_app/list.dart';
- import 'package:shared_preferences/shared_preferences.dart';
- import 'const.dart';
- // class response json
- class Response {
- final String status;
- final String message;
- Response({this.status, this.message});
- factory Response.fromJson(Map<String, dynamic> json) {
- return Response(
- status: json['status'],
- message: json['message'],
- );
- }
- }
- class Login extends StatefulWidget {
- @override
- LoginState createState() => new LoginState();
- }
- class LoginState extends State<Login> {
- // variabel member class
- final _username = TextEditingController();
- final _password = TextEditingController();
- // member response
- String _response = '';
- bool _apiCall = false;
- // login shared prefs
- bool alreadyLogin = false;
- // fungsi untuk kirim http post
- Future<Response> post(String url,var body)async{
- return await http
- .post(Uri.encodeFull(url), body: body, headers: {"Accept":"application/json"})
- .then((http.Response response) {
- final int statusCode = response.statusCode;
- if (statusCode < 200 || statusCode > 400 || json == null) {
- throw new Exception("Error while fetching data");
- }
- return Response.fromJson(json.decode(response.body));
- });
- }
- // fungsi panggil API
- void _callPostAPI() {
- post(
- Constant.apiLogin,
- {
- 'username': _username.text,
- 'password': _password.text
- }).then((response) async {
- // jika respon normal
- setState(() {
- _apiCall = false;
- _response = response.message;
- });
- if (response.status == "success") {
- // simpan shared prefs sudah login
- final prefs = await SharedPreferences.getInstance();
- setState(() {
- alreadyLogin = true;
- prefs.setBool('login', alreadyLogin);
- });
- // menuju route list product
- // Navigator.push(
- // context,
- // MaterialPageRoute(builder: (context) => listProduct(context))
- // );
- Navigator.pushNamed(context,'/list');
- }
- },
- // jika respon error
- onError: (error) {
- _apiCall = false;
- _response = error.toString();
- }
- );
- }
- Widget progressWidget() {
- if (_apiCall)
- // jika masih proses kirim API
- return AlertDialog(
- content: new Column(
- children: <Widget>[
- CircularProgressIndicator(),
- Text("Please wait")
- ],
- ),
- );
- else
- // jika sudah selesai kirim API
- return Center(
- child: Text(
- _response,
- style: new TextStyle(fontSize: 15.0),
- ),
- );
- }
- Future<bool> getLoginStatus() async{
- final prefs = await SharedPreferences.getInstance();
- bool loginStatus = prefs.getBool('login') ?? false;
- print('login status $loginStatus');
- return loginStatus;
- }
- @override
- Widget build(BuildContext context) {
- return FutureBuilder<bool>(
- future: getLoginStatus(),
- builder: (context, snapshot) {
- return (snapshot.data) ?
- // jika alreadyLogin = true
- listProduct(context) :
- // jika alreadyLogin = false
- loginForm();
- },
- );
- }
- Widget loginForm() {
- return Scaffold(
- appBar: new AppBar(
- title: const Text('W2 Flutter'),
- automaticallyImplyLeading: false,
- ),
- body: SafeArea(
- child: ListView(
- padding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),
- children: <Widget>[
- // nama
- TextField(
- controller: _username,
- decoration: InputDecoration(
- filled: true,
- labelText: 'Username'
- ),
- ),
- // spasi
- SizedBox(height: 5.0),
- // alamat
- TextField(
- controller: _password,
- decoration: InputDecoration(
- filled: true,
- labelText: 'Password'
- ),
- obscureText: true,
- ),
- // spasi
- SizedBox(height: 10.0),
- // tombol
- RaisedButton(
- child: Text('LOGIN'),
- onPressed: () {
- setState(() {
- _apiCall = true;
- });
- _callPostAPI();
- /*
- return showDialog(
- context: context,
- builder: (context) {
- return AlertDialog(
- content: Text('Username: ${_username.text}\nPassword: ${_password.text}'),
- );
- },
- );
- */
- },
- ),
- // panggil loading widget
- progressWidget()
- ],
- )
- )
- );
- }
- }
- // main.dart
- import 'package:flutter/material.dart';
- import 'package:flutter_app/entry.dart';
- import 'package:flutter_app/list.dart';
- import 'sample_list.dart';
- //import 'tabs.dart';
- import 'login.dart';
- void main() => runApp(MyApp());
- class MyApp extends StatelessWidget {
- @override
- Widget build(BuildContext context) {
- return MaterialApp(
- title: 'Flutter Demo',
- theme: ThemeData(
- primarySwatch: Colors.green,
- ),
- home: new Login(),
- initialRoute: '/login',
- routes: {
- '/login' : (context) => Login(),
- '/list' : (context) => listProduct(context),
- '/entry' : (context) => EntryData(),
- },
- );
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement