· 6 years ago · Oct 08, 2019, 01:58 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
15 final String nama,email,level;
16 Response({this.status, this.message,this.nama,this.email,this.level});
17
18
19 factory Response.fromJson(Map<String, dynamic> json) {
20 return Response(
21 status: json['status'],
22 message: json['message'],
23 level: json['level'],
24
25 );
26 }
27}
28
29
30class Menu_Login extends StatefulWidget{
31 @override
32 Menu_LoginState createState()=> Menu_LoginState();
33}
34class Menu_LoginState extends State<Menu_Login>{
35
36
37 final _formKey = GlobalKey<FormState>();
38
39 String nama ='';
40 String email = '';
41
42
43 // variabel member class
44 final username = TextEditingController();
45 final password = TextEditingController();
46
47 // member response
48 String _response = '';
49 bool _apiCall = false;
50
51
52 // login shared prefs
53 bool alreadyLogin = false;
54
55
56 // fungsi untuk kirim http post
57 Future<Response> post(String url,var body)async{
58 return await http
59 .post(Uri.encodeFull(url), body: body, headers: {"Accept":"application/json"})
60 .then((http.Response response) {
61
62 final int statusCode = response.statusCode;
63
64 if (statusCode < 200 || statusCode > 400 || json == null) {
65 throw new Exception("Error while fetching data");
66 }
67 return Response.fromJson(json.decode(response.body));
68 });
69 }
70
71
72
73
74 // fungsi panggil API
75 void _callPostAPI() {
76 post(
77 'http://adityo.xyz/mata_rakyat/mr_login.php',
78 {
79 'username': username.text,
80 'password': password.text,
81
82 }).then((response) async {
83 // jika respon normal
84 setState(() {
85 _apiCall = false;
86 _response = response.message;
87
88
89 });
90
91
92
93 if (response.status == "success") {
94
95 // simpan shared prefs sudah login
96 // final prefs = await SharedPreferences.getInstance();
97
98 setState(()async {
99 alreadyLogin = true;
100 final prefs = await SharedPreferences.getInstance();
101 prefs.setBool('login', alreadyLogin);
102
103 });
104 print(response.level);
105
106
107 // menuju route Halaman utama
108 if (response.level == "admin") {
109 Navigator.push(
110 context,
111 MaterialPageRoute(builder: (context) => Halaman_admin())
112 );
113 }else {
114 Navigator.push(
115 context,
116 MaterialPageRoute(builder: (context) => Halaman_Input())
117 );
118 }
119
120
121
122
123 }
124
125 },
126 // jika respon error
127 onError: (error) {
128 _apiCall = false;
129 _response = error.toString();
130 }
131 );
132 }
133
134 Widget progressWidget() {
135 if (_apiCall)
136 // jika masih proses kirim API
137 return AlertDialog(
138 content: new Column(
139 children: <Widget>[
140 CircularProgressIndicator(),
141 Text("Please wait")
142 ],
143 ),
144 );
145 else
146 // jika sudah selesai kirim API
147 return Center(
148 child: Text(
149 _response,
150 style: new TextStyle(fontSize: 15.0),
151 ),
152 );
153 }
154
155 Future<bool> getLoginStatus() async{
156 final prefs = await SharedPreferences.getInstance();
157 bool loginStatus = prefs.getBool('login') ?? false;
158 print('login status $loginStatus');
159
160 return loginStatus;
161
162 }
163
164 @override
165 Widget build(BuildContext context) {
166 return FutureBuilder<bool>(
167 future: getLoginStatus(),
168 builder: (context, snapshot) {
169 return (snapshot.data) ?
170 // jika sudah login tampilkan list product
171 new Halaman_Input():
172
173 // jika belum login tampilkan form login
174 loginForm();
175 },
176 );
177 }
178
179 Widget loginForm() {
180
181 return Scaffold(
182 backgroundColor: Colors.white,
183
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 validator: (value) {
258 if (value.length<4) {
259 return 'Password Minimal 4 Karakter';
260 }
261 return null;
262
263 },
264 ),
265 ),
266 Padding(padding: EdgeInsets.only(top: 5)),
267 Row(
268 mainAxisAlignment: MainAxisAlignment.spaceBetween,
269 children: <Widget>[
270
271 FlatButton(
272 child: Text(
273 "Lupa Password?",
274 style: TextStyle(
275 fontSize: 15,
276 color: Colors.white,
277 ),
278 ),
279 onPressed: () {},
280 ),
281 ],
282 ),
283 RaisedButton(
284 child: Text('Login',style: TextStyle(color: Colors.white,fontSize: 18),),
285 color: Colors.lightBlueAccent,
286 padding: EdgeInsets.symmetric(horizontal: 110),
287 shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
288 onPressed: () {
289 if (_formKey.currentState.validate()) {
290 _formKey.currentState.save();
291
292 setState(() {
293 _apiCall = true;
294 });
295 _callPostAPI();
296 }
297 }
298 ),
299
300 progressWidget(),
301
302 Divider(
303 color: Colors.grey,
304 ),
305
306 Row(
307
308 mainAxisAlignment: MainAxisAlignment.center,
309 children: <Widget>[
310 Text(
311 "Tidak Punya Akun?",
312 style: TextStyle(
313 color: Colors.white,
314 fontSize: 13,
315 fontWeight: FontWeight.w800,
316 ),
317 ),
318 FlatButton(
319 child: Text(
320 "Buat Akun.",
321 style: TextStyle(
322
323 fontSize: 15,
324 color: Colors.white,
325
326 ),
327 ),
328 onPressed: () {
329 Navigator.push(
330 context,
331 MaterialPageRoute(
332 builder: (BuildContext context) {
333 return Registrasi();
334 }
335 )
336 );
337 },
338 ),
339 ],
340 ),
341
342 ],
343 ),
344
345 )
346 ],
347 ),
348 ),
349 ),
350 ),
351 );
352
353 }
354}