Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // product list
- import 'package:flutter/material.dart';
- import 'dart:convert';
- import 'dart:async';
- import 'package:http/http.dart' as http;
- import 'package:flutter/foundation.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('http://192.3.168.178/restapi/getproduct.php');
- 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 () {
- return new Scaffold(
- appBar: new AppBar(
- title: const Text("W2 Flutter"),
- ),
- body: new ProductList(),
- floatingActionButton: FloatingActionButton(
- child: Icon(Icons.add),
- onPressed: null
- ),
- drawer: Drawer(
- child: ListView(
- children: <Widget>[
- 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: () {
- },
- ),
- ],
- ),
- ),
- );
- }
- // login
- import 'package:flutter/material.dart';
- import 'dart:async';
- import 'dart:convert';
- import 'package:http/http.dart' as http;
- import 'package:latihan/product_list.dart';
- import 'package:shared_preferences/shared_preferences.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(
- 'http://192.3.168.178/restapi/login.php',
- {
- '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())
- );
- }
- },
- // 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() :
- // jika alreadyLogin = false
- loginForm();
- },
- );
- }
- Widget loginForm() {
- return Scaffold(
- appBar: new AppBar(
- title: const Text('W2 Flutter'),
- ),
- 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()
- ],
- )
- )
- );
- }
- }
- // tabs
- import 'package:flutter/material.dart';
- import 'sample_list.dart';
- import 'product_list.dart';
- class TabDemo extends StatelessWidget {
- @override
- Widget build(BuildContext context) {
- // TODO: implement build
- return DefaultTabController(
- length: 3,
- child: Scaffold(
- appBar: AppBar(
- title: Text('Tab demo'),
- bottom: TabBar(
- tabs: [
- Tab(icon: Icon(Icons.directions_car)),
- Tab(icon: Icon(Icons.directions_transit)),
- Tab(icon: Icon(Icons.directions_bike)),
- ]
- ),
- ),
- body: TabBarView(
- children: [
- //Icon(Icons.directions_car),
- //Text('ini text'),
- new ProductList(),
- new ImageList(),
- Icon(Icons.directions_bike),
- ]
- ),
- ),
- );
- }
- }
- // main
- import 'package:flutter/material.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(),
- );
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement