Advertisement
Guest User

Untitled

a guest
Jan 22nd, 2019
163
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 10.53 KB | None | 0 0
  1. // product list
  2. import 'package:flutter/material.dart';
  3. import 'dart:convert';
  4. import 'dart:async';
  5. import 'package:http/http.dart' as http;
  6. import 'package:flutter/foundation.dart';
  7.  
  8. // class untuk objek json
  9. class Product {
  10. final String id;
  11. final String nama_produk;
  12. final String kategori;
  13. final String expired_date;
  14. final String nomor_rak;
  15. final String scan_code;
  16. final String discount;
  17.  
  18. Product({this.id, this.nama_produk, this.kategori, this.expired_date,
  19. this.nomor_rak, this.scan_code, this.discount});
  20.  
  21. factory Product.fromJson(Map<String, dynamic> json) {
  22. return Product(
  23. id: json['id'] as String,
  24. nama_produk: json['nama_produk'] as String,
  25. kategori: json['kategori'] as String,
  26. expired_date: json['expired_date'] as String,
  27. nomor_rak: json['nomor_rak'] as String,
  28. scan_code: json['scan_code'] as String,
  29. discount: json['discount'] as String,
  30. );
  31. }
  32. }
  33.  
  34. // fungsi parse foto untuk mengubah dari string json ke array List<Photo>
  35. List<Product> parseProduct(String responseBody) {
  36. final parsed = json.decode(responseBody).cast<Map<String,dynamic>>();
  37. return parsed.map<Product>((json)=>Product.fromJson(json)).toList();
  38. }
  39.  
  40. // fungsi fetch untuk mengubah dari end point api ke array List<Photo>
  41. Future<List<Product>> fetchProduct(http.Client client) async {
  42. final response = await client.get('http://192.3.168.178/restapi/getproduct.php');
  43. return compute(parseProduct, response.body);
  44. }
  45.  
  46. class ProductList extends StatelessWidget {
  47. @override
  48. Widget build(BuildContext context) {
  49. return FutureBuilder <List<Product>> (
  50. future: fetchProduct(http.Client()),
  51. builder: (context, snapshot) {
  52. if (snapshot.hasError) print(snapshot.error);
  53. return (snapshot.hasData) ? ProductListBuilder(photos: snapshot.data):
  54. Center(child: CircularProgressIndicator());
  55. }
  56. );
  57. }
  58. }
  59.  
  60. class ProductListBuilder extends StatelessWidget {
  61. final List<Product> photos;
  62. ProductListBuilder({Key key, this.photos}) : super(key : key);
  63.  
  64. @override
  65. Widget build(BuildContext context) {
  66. return ListView.builder(
  67. itemCount: photos.length,
  68. itemBuilder: (context, index) {
  69. return ListTile (
  70. // title: Text('Title '+photos[index].title),
  71. title : Column (
  72. children: <Widget>[
  73. ListTile(
  74. title: Text("Nama Produk : ${photos[index].nama_produk}"),
  75. subtitle: Text(
  76. "Kategori : ${photos[index].kategori} \n"+
  77. "Expired date : ${photos[index].expired_date} \n" +
  78. "Nomor Rak : ${photos[index].nomor_rak} \n" +
  79. "Scan code : ${photos[index].scan_code} \n" +
  80. "Diskon : ${photos[index].discount} \n"
  81. ),
  82. ),
  83. Divider(),
  84. ],
  85. ),
  86. );
  87. },
  88. );
  89. }
  90. }
  91.  
  92. Widget listProduct () {
  93. return new Scaffold(
  94. appBar: new AppBar(
  95. title: const Text("W2 Flutter"),
  96. ),
  97. body: new ProductList(),
  98. floatingActionButton: FloatingActionButton(
  99. child: Icon(Icons.add),
  100. onPressed: null
  101. ),
  102. drawer: Drawer(
  103. child: ListView(
  104. children: <Widget>[
  105. ListTile(
  106. title: Text('Profile'),
  107. trailing: Icon(Icons.person),
  108. leading: Icon(Icons.arrow_right),
  109. onTap: () {
  110.  
  111. },
  112. ),
  113. ListTile(
  114. title: Text('Favorites'),
  115. trailing: Icon(Icons.favorite),
  116. leading: Icon(Icons.arrow_right),
  117. onTap: () {
  118.  
  119. },
  120. ),
  121. ListTile(
  122. title: Text('Settings'),
  123. trailing: Icon(Icons.settings),
  124. leading: Icon(Icons.arrow_right),
  125. onTap: () {
  126.  
  127. },
  128. ),
  129. ListTile(
  130. title: Text('Logout'),
  131. trailing: Icon(Icons.exit_to_app),
  132. leading: Icon(Icons.arrow_right),
  133. onTap: () {
  134.  
  135. },
  136. ),
  137. ],
  138. ),
  139. ),
  140. );
  141. }
  142.  
  143. // login
  144. import 'package:flutter/material.dart';
  145. import 'dart:async';
  146. import 'dart:convert';
  147. import 'package:http/http.dart' as http;
  148. import 'package:latihan/product_list.dart';
  149. import 'package:shared_preferences/shared_preferences.dart';
  150.  
  151. // class response json
  152. class Response {
  153. final String status;
  154. final String message;
  155.  
  156. Response({this.status, this.message});
  157.  
  158. factory Response.fromJson(Map<String, dynamic> json) {
  159. return Response(
  160. status: json['status'],
  161. message: json['message'],
  162. );
  163. }
  164. }
  165.  
  166.  
  167. class Login extends StatefulWidget {
  168. @override
  169. LoginState createState() => new LoginState();
  170. }
  171.  
  172. class LoginState extends State<Login> {
  173.  
  174. // variabel member class
  175. final _username = TextEditingController();
  176. final _password = TextEditingController();
  177.  
  178. // member response
  179. String _response = '';
  180. bool _apiCall = false;
  181.  
  182. // login shared prefs
  183. bool alreadyLogin = false;
  184.  
  185. // fungsi untuk kirim http post
  186. Future<Response> post(String url,var body)async{
  187. return await http
  188. .post(Uri.encodeFull(url), body: body, headers: {"Accept":"application/json"})
  189. .then((http.Response response) {
  190.  
  191. final int statusCode = response.statusCode;
  192.  
  193. if (statusCode < 200 || statusCode > 400 || json == null) {
  194. throw new Exception("Error while fetching data");
  195. }
  196. return Response.fromJson(json.decode(response.body));
  197. });
  198. }
  199.  
  200. // fungsi panggil API
  201. void _callPostAPI() {
  202. post(
  203. 'http://192.3.168.178/restapi/login.php',
  204. {
  205. 'username': _username.text,
  206. 'password': _password.text
  207. }).then((response) async {
  208. // jika respon normal
  209. setState(() {
  210. _apiCall = false;
  211. _response = response.message;
  212. });
  213.  
  214. if (response.status == "success") {
  215. // simpan shared prefs sudah login
  216. final prefs = await SharedPreferences.getInstance();
  217. setState(() {
  218. alreadyLogin = true;
  219. prefs.setBool('login', alreadyLogin);
  220. });
  221.  
  222. // menuju route list product
  223. Navigator.push(
  224. context,
  225. MaterialPageRoute(builder: (context) => listProduct())
  226. );
  227. }
  228.  
  229. },
  230. // jika respon error
  231. onError: (error) {
  232. _apiCall = false;
  233. _response = error.toString();
  234. }
  235. );
  236. }
  237.  
  238. Widget progressWidget() {
  239. if (_apiCall)
  240. // jika masih proses kirim API
  241. return AlertDialog(
  242. content: new Column(
  243. children: <Widget>[
  244. CircularProgressIndicator(),
  245. Text("Please wait")
  246. ],
  247. ),
  248. );
  249. else
  250. // jika sudah selesai kirim API
  251. return Center(
  252. child: Text(
  253. _response,
  254. style: new TextStyle(fontSize: 15.0),
  255. ),
  256. );
  257. }
  258.  
  259. Future<bool> getLoginStatus() async{
  260. final prefs = await SharedPreferences.getInstance();
  261. bool loginStatus = prefs.getBool('login') ?? false;
  262. print('login status $loginStatus');
  263. return loginStatus;
  264. }
  265.  
  266. @override
  267. Widget build(BuildContext context) {
  268. return FutureBuilder<bool>(
  269. future: getLoginStatus(),
  270. builder: (context, snapshot) {
  271. return (snapshot.data) ?
  272. // jika alreadyLogin = true
  273. listProduct() :
  274. // jika alreadyLogin = false
  275. loginForm();
  276. },
  277. );
  278. }
  279.  
  280. Widget loginForm() {
  281. return Scaffold(
  282. appBar: new AppBar(
  283. title: const Text('W2 Flutter'),
  284. ),
  285. body: SafeArea(
  286. child: ListView(
  287. padding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),
  288. children: <Widget>[
  289. // nama
  290. TextField(
  291. controller: _username,
  292. decoration: InputDecoration(
  293. filled: true,
  294. labelText: 'Username'
  295. ),
  296. ),
  297. // spasi
  298. SizedBox(height: 5.0),
  299. // alamat
  300. TextField(
  301. controller: _password,
  302. decoration: InputDecoration(
  303. filled: true,
  304. labelText: 'Password'
  305. ),
  306. obscureText: true,
  307. ),
  308. // spasi
  309. SizedBox(height: 10.0),
  310. // tombol
  311. RaisedButton(
  312. child: Text('LOGIN'),
  313. onPressed: () {
  314.  
  315. setState(() {
  316. _apiCall = true;
  317. });
  318. _callPostAPI();
  319. /*
  320. return showDialog(
  321. context: context,
  322. builder: (context) {
  323. return AlertDialog(
  324. content: Text('Username: ${_username.text}\nPassword: ${_password.text}'),
  325. );
  326. },
  327. );
  328. */
  329. },
  330. ),
  331.  
  332. // panggil loading widget
  333. progressWidget()
  334. ],
  335. )
  336. )
  337. );
  338.  
  339. }
  340. }
  341.  
  342. // tabs
  343. import 'package:flutter/material.dart';
  344. import 'sample_list.dart';
  345. import 'product_list.dart';
  346.  
  347. class TabDemo extends StatelessWidget {
  348. @override
  349. Widget build(BuildContext context) {
  350. // TODO: implement build
  351. return DefaultTabController(
  352. length: 3,
  353. child: Scaffold(
  354. appBar: AppBar(
  355. title: Text('Tab demo'),
  356. bottom: TabBar(
  357. tabs: [
  358. Tab(icon: Icon(Icons.directions_car)),
  359. Tab(icon: Icon(Icons.directions_transit)),
  360. Tab(icon: Icon(Icons.directions_bike)),
  361. ]
  362. ),
  363. ),
  364. body: TabBarView(
  365. children: [
  366. //Icon(Icons.directions_car),
  367. //Text('ini text'),
  368. new ProductList(),
  369. new ImageList(),
  370. Icon(Icons.directions_bike),
  371. ]
  372. ),
  373. ),
  374. );
  375. }
  376.  
  377. }
  378.  
  379. // main
  380. import 'package:flutter/material.dart';
  381. import 'sample_list.dart';
  382. import 'tabs.dart';
  383. import 'login.dart';
  384.  
  385. void main() => runApp(MyApp());
  386.  
  387. class MyApp extends StatelessWidget {
  388. @override
  389. Widget build(BuildContext context) {
  390. return MaterialApp(
  391. title: 'Flutter Demo',
  392. theme: ThemeData(
  393. primarySwatch: Colors.green,
  394. ),
  395. home: new Login(),
  396. );
  397. }
  398. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement