· 6 years ago · Oct 08, 2019, 11:36 AM
1import 'package:flutter/material.dart';
2import 'package:mata_rakyat/registrasi.dart';
3import 'package:mata_rakyat/Halaman_Input.dart';
4import 'package:shared_preferences/shared_preferences.dart';
5import 'dart:async';
6import 'dart:convert';
7import 'package:http/http.dart' as http;
8import 'package:mata_rakyat/halaman_admin.dart';
9
10
11class Response {
12 final String status;
13 final String message;
14 final String nama,email,level;
15 Response({this.status, this.message,this.nama,this.email,this.level});
16
17
18 factory Response.fromJson(Map<String, dynamic> json) {
19 return Response(
20 status: json['status'],
21 message: json['message'],
22 level: json['level'],
23
24 );
25 }
26}
27
28
29class Menu_Login extends StatefulWidget{
30 @override
31 Menu_LoginState createState()=> Menu_LoginState();
32}
33class Menu_LoginState extends State<Menu_Login>{
34
35
36 final _formKey = GlobalKey<FormState>();
37
38
39
40 // variabel member class
41 final username = TextEditingController();
42 final password = TextEditingController();
43
44 // member response
45 String _response = '';
46 bool _apiCall = false;
47 String nama = '';
48 String email = '';
49
50
51 // login shared prefs
52 bool alreadyLogin = false;
53
54
55 // fungsi untuk kirim http post
56 Future<Response> post(String url,var body)async{
57 return await http
58 .post(Uri.encodeFull(url), body: body, headers: {"Accept":"application/json"})
59 .then((http.Response response) {
60
61 final int statusCode = response.statusCode;
62
63 if (statusCode < 200 || statusCode > 400 || json == null) {
64 throw new Exception("Error while fetching data");
65 }
66 return Response.fromJson(json.decode(response.body));
67 });
68 }
69
70
71
72
73 // fungsi panggil API
74 void _callPostAPI() {
75 post(
76 'http://adityo.xyz/mata_rakyat/mr_login.php',
77 {
78 'username': username.text,
79 'password': password.text,
80
81 }).then((response) async {
82 // jika respon normal
83 setState(() {
84 _apiCall = false;
85 _response = response.message;
86 nama = '';
87 email = '';
88 });
89
90
91
92 if (response.status == "success") {
93
94 // simpan shared prefs sudah login
95 // final prefs = await SharedPreferences.getInstance();
96
97 setState(()async {
98 alreadyLogin = true;
99 final prefs = await SharedPreferences.getInstance();
100 prefs.setBool('login', alreadyLogin);
101 prefs.getString(nama);
102 prefs.getString(email);
103 print(nama);
104 print(email);
105
106 });
107 print(response.level);
108
109
110 // menuju route Halaman utama
111 if (response.level == "admin") {
112 Navigator.push(
113 context,
114 MaterialPageRoute(builder: (context) => Halaman_admin())
115 );
116 }else {
117 Navigator.push(
118 context,
119 MaterialPageRoute(builder: (context) => Halaman_Input())
120 );
121 }
122 }
123
124 },
125 // jika respon error
126 onError: (error) {
127 _apiCall = false;
128 _response = error.toString();
129 }
130 );
131 }
132
133 Widget progressWidget() {
134 if (_apiCall)
135 // jika masih proses kirim API
136 return AlertDialog(
137 content: new Column(
138 children: <Widget>[
139 CircularProgressIndicator(),
140 Text("Please wait")
141 ],
142 ),
143 );
144 else
145 // jika sudah selesai kirim API
146 return Center(
147 child: Text(
148 _response,
149 style: new TextStyle(fontSize: 15.0),
150 ),
151 );
152 }
153
154 Future<bool> getLoginStatus() async{
155 final prefs = await SharedPreferences.getInstance();
156 bool loginStatus = prefs.getBool('login') ?? false;
157 String nama = prefs.getString(nama);
158 print('login status $loginStatus');
159
160
161 return loginStatus;
162
163 }
164
165 @override
166 Widget build(BuildContext context) {
167 return FutureBuilder<bool>(
168 future: getLoginStatus(),
169 builder: (context, snapshot) {
170 return (snapshot.data) ?
171 // jika sudah login tampilkan list product
172 new Halaman_Input():
173
174 // jika belum login tampilkan form login
175 loginForm();
176 },
177 );
178 }
179
180 Widget loginForm() {
181
182 return Scaffold(
183 backgroundColor: Colors.white,
184
185 body: SingleChildScrollView(
186 child: Container(
187 padding: EdgeInsets.only(top: 50),
188 height: 800,
189 decoration: new BoxDecoration(
190 image: DecorationImage(
191 image: NetworkImage('https://previews.123rf.com/images/gloriaolsy/gloriaolsy1905/gloriaolsy190536020/125761170-colorful-gradient-color-background-wallpaper-for-greeting-card-flyer-poster-brochure-banner-calendar.jpg'),
192 fit: BoxFit.cover
193 ),
194 ),
195 child: Form(
196 key: _formKey,
197 child: Column(
198 children: <Widget>[
199
200
201 Container(
202
203
204 margin: EdgeInsets.all(15),
205
206
207
208
209
210 child: Column(
211 children: <Widget>[
212 Image.asset('assets/images/Berita.png', height: 80, width: 80,),
213 Padding(padding: EdgeInsets.only(top: 5)),
214 Text("WELCOME",style: TextStyle(fontSize: 18,fontWeight: FontWeight.w800,color: Colors.white),),
215 Padding(padding: EdgeInsets.only(top: 10)),
216
217
218 Container(
219
220 margin: EdgeInsets.only(right: 15,left: 15),
221 child: TextFormField(
222 controller: username,
223 style: TextStyle(color: Colors.white),
224
225 decoration: InputDecoration(
226
227
228 prefixIcon: Icon(Icons.email,color: Colors.white),
229 hintText: 'Username',
230 contentPadding: EdgeInsets.fromLTRB(20, 10, 20, 10),
231 border: OutlineInputBorder(borderRadius: BorderRadius.circular(10)),
232
233 ),
234 validator: (value) {
235 if (value.isEmpty) {
236 return 'Username Tidak Boleh Kosong';
237 }
238 return null;
239
240 },
241 ),
242 ),
243 Padding(padding: EdgeInsets.only(top: 20)),
244
245 Container(
246
247 margin: EdgeInsets.only(right: 15,left: 15),
248 child: TextFormField(
249 controller: password,
250 style: TextStyle(color: Colors.white),
251 decoration: InputDecoration(
252 prefixIcon: Icon(Icons.vpn_key,color: Colors.white),
253 hintText: 'Password',
254 contentPadding: EdgeInsets.fromLTRB(20, 10, 20, 10),
255 border: OutlineInputBorder(borderRadius: BorderRadius.circular(10)),
256
257 ),
258 obscureText: true,
259 validator: (value) {
260 if (value.length<4) {
261 return 'Password Minimal 4 Karakter';
262 }
263 return null;
264
265 },
266 ),
267 ),
268 Padding(padding: EdgeInsets.only(top: 5)),
269 Row(
270 mainAxisAlignment: MainAxisAlignment.spaceBetween,
271 children: <Widget>[
272
273 FlatButton(
274 child: Text(
275 "Lupa Password?",
276 style: TextStyle(
277 fontSize: 15,
278 color: Colors.white,
279 ),
280 ),
281 onPressed: () {},
282 ),
283 ],
284 ),
285 RaisedButton(
286 child: Text('Login',style: TextStyle(color: Colors.white,fontSize: 18),),
287 color: Colors.lightBlueAccent,
288 padding: EdgeInsets.symmetric(horizontal: 110),
289 shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
290 onPressed: () {
291 if (_formKey.currentState.validate()) {
292 _formKey.currentState.save();
293
294 setState(() {
295 _apiCall = true;
296 });
297 _callPostAPI();
298 }
299 }
300 ),
301
302 progressWidget(),
303
304 Divider(
305 color: Colors.grey,
306 ),
307
308 Row(
309
310 mainAxisAlignment: MainAxisAlignment.center,
311 children: <Widget>[
312 Text(
313 "Tidak Punya Akun?",
314 style: TextStyle(
315 color: Colors.white,
316 fontSize: 13,
317 fontWeight: FontWeight.w800,
318 ),
319 ),
320 FlatButton(
321 child: Text(
322 "Buat Akun.",
323 style: TextStyle(
324
325 fontSize: 15,
326 color: Colors.white,
327
328 ),
329 ),
330 onPressed: () {
331 Navigator.push(
332 context,
333 MaterialPageRoute(
334 builder: (BuildContext context) {
335 return Registrasi();
336 }
337 )
338 );
339 },
340 ),
341 ],
342 ),
343
344 ],
345 ),
346
347 )
348 ],
349 ),
350 ),
351 ),
352 ),
353 );
354
355 }
356}