Flutter Dasar
Pertemuan #7
Toko Kopi Haqiqi Cilebut, 17 Agustus 2019
oleh : k4ilham & LT
Login API
pubspec.yaml
name: flutter_login
description: A new Flutter project.
# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0+1
environment:
sdk: ">=2.1.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^0.1.2
shared_preferences: ^0.5.3+4
http: ^0.12.0+2
sweetalert: ^0.0.1
device_id: ^0.1.3
dev_dependencies:
flutter_test:
sdk: flutter
# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec
# The following section is specific to Flutter.
flutter:
# The following line ensures that the Material Icons font is
# included with your application, so that you can use the icons in
# the material Icons class.
uses-material-design: true
# To add assets to your application, add an assets section, like this:
# assets:
# - images/a_dot_burr.jpeg
# - images/a_dot_ham.jpeg
# An image asset can refer to one or more resolution-specific "variants", see
# https://flutter.dev/assets-and-images/#resolution-aware.
# For details regarding adding assets from package dependencies, see
# https://flutter.dev/assets-and-images/#from-packages
# To add custom fonts to your application, add a fonts section here,
# in this "flutter" section. Each entry in this list should have a
# "family" key with the font family name, and a "fonts" key with a
# list giving the asset and other descriptors for the font. For
# example:
# fonts:
# - family: Schyler
# fonts:
# - asset: fonts/Schyler-Regular.ttf
# - asset: fonts/Schyler-Italic.ttf
# style: italic
# - family: Trajan Pro
# fonts:
# - asset: fonts/TrajanPro.ttf
# - asset: fonts/TrajanPro_Bold.ttf
# weight: 700
#
# For details regarding fonts from package dependencies,
# see https://flutter.dev/custom-fonts/#from-packages
routes.dart
import 'package:flutter/material.dart';
import 'login.dart';
import 'home.dart';
class Routes {
Routes() {
runApp(new MaterialApp(
title: "Login System",
debugShowCheckedModeBanner: false,
home: new Login(),
onGenerateRoute: (RouteSettings settings) {
switch (settings.name) {
case '/login':
return new MyCustomRoute(
builder: (_) => new Login(),
settings: settings,
);
case '/home':
return new MyCustomRoute(
builder: (_) => new Home(),
settings: settings,
);
}
},
));
}
}
class MyCustomRoute<T> extends MaterialPageRoute<T> {
MyCustomRoute({WidgetBuilder builder, RouteSettings settings})
: super(builder: builder, settings: settings);
}
main.dart
import 'package:flutter_login/routes.dart';
void main() {
new Routes();
}
login.dart
import 'home.dart';
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:sweetalert/sweetalert.dart';
import 'package:device_id/device_id.dart';
import 'package:http/http.dart' as http;
import 'package:flutter/foundation.dart';
import 'package:shared_preferences/shared_preferences.dart';
class Login extends StatefulWidget {
Login({Key key}) : super(key: key);
_LoginState createState() => _LoginState();
}
class _LoginState extends State<Login> {
final formKey = GlobalKey<FormState>();
final nameController = TextEditingController();
final passController = TextEditingController();
List data;
String _deviceid = 'Unknown';
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: Icon(Icons.android),
title: Text('Login Form'),
),
body: Form(
key: formKey,
child: Column(
children: <Widget>[
_username(context),
_password(context),
_buttonLogin(context),
Text("id :" + _deviceid.toString()),
],
),
),
);
}
@override
void initState() {
super.initState();
initDeviceId();
_cekLogin();
}
Future<void> initDeviceId() async {
String deviceid;
deviceid = await DeviceId.getID;
if (!mounted) return;
setState(() {
_deviceid = deviceid;
});
}
Future _getLogin(String userName, String userPass, String token) async {
String url = "http://kailham.com/apiSikar/login?userName=" +
userName +
"&userPass=" +
userPass +
"&token=" +
token;
var res = await http
.get(Uri.encodeFull(url), headers: {'accept': 'application/json'});
var response = json.decode(res.body);
setState(() {
data = response["data"];
});
if (response['status'] == true) {
SharedPreferences pref = await SharedPreferences.getInstance();
pref.setBool("isLogin", true);
pref.setString("dataMessage", response['message']);
} else {
SharedPreferences pref = await SharedPreferences.getInstance();
pref.setBool("isLogin", false);
pref.setString("dataMessage", response['message']);
}
}
Future _cekLogin() async {
//SHAREDPREFERENCES
SharedPreferences pref = await SharedPreferences.getInstance();
if (pref.getBool("isLogin")) {
Navigator.push(
context, MaterialPageRoute(builder: (context) => new Home()));
}
}
String validatePass(String value) {
if (value.length < 4) {
return 'Password Minimal 4 Karakter';
}
return null;
}
String validateUser(String value) {
if (value.isEmpty) {
return 'Username harus diisi';
}
return null;
}
void _showAlert(String pesan) {
SweetAlert.show(context,
title: "ERROR", subtitle: pesan, style: SweetAlertStyle.error);
}
void submit() async {
if (formKey.currentState.validate()) {
formKey.currentState.save();
print(nameController.value.text);
final userName = nameController.value.text;
final userPass = passController.value.text;
final token = _deviceid;
_getLogin(userName, userPass, token);
FocusScope.of(context).requestFocus(new FocusNode());
// Simulate a service call
Future.delayed(Duration(seconds: 1), () async {
SharedPreferences pref = await SharedPreferences.getInstance();
if (pref.getBool("isLogin") == true) {
pref.setString("karNik", data[0]['karNik']);
pref.setString("karNama", data[0]['karNama']);
//pindah ke home
SweetAlert.show(context,
subtitle: "Checking Username...", style: SweetAlertStyle.loading);
new Future.delayed(new Duration(seconds: 2), () {
Navigator.pushReplacementNamed(context, "/home");
});
} else {
String pesan = pref.getString("dataMessage").toUpperCase().toString();
_showAlert(pesan);
}
});
}
}
Widget _username(BuildContext context) {
return Padding(
padding: EdgeInsets.all(8.0),
child: TextFormField(
controller: nameController,
validator: validateUser,
key: Key('username'),
decoration:
InputDecoration(hintText: 'username', labelText: 'username'),
style: TextStyle(fontSize: 20.0, color: Colors.black),
),
);
}
Widget _password(BuildContext context) {
return Padding(
padding: EdgeInsets.all(8.0),
child: TextFormField(
controller: passController,
validator: validatePass,
key: Key('password'),
decoration:
InputDecoration(hintText: 'password', labelText: 'password'),
style: TextStyle(fontSize: 20.0, color: Colors.black),
obscureText: true,
),
);
}
Widget _buttonLogin(BuildContext context) {
return Padding(
padding: EdgeInsets.all(8.0),
child: new InkWell(
onTap: () {
submit();
},
child: new Container(
//width: 100.0,
height: 50.0,
decoration: new BoxDecoration(
color: Colors.blueAccent,
border: new Border.all(color: Colors.white, width: 2.0),
borderRadius: new BorderRadius.circular(10.0),
),
child: new Center(
child: new Text(
'Login',
style: new TextStyle(fontSize: 18.0, color: Colors.white),
),
),
),
),
);
}
}
home.dart
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:sweetalert/sweetalert.dart';
import 'login.dart';
import 'dart:io';
class Home extends StatefulWidget {
Home({Key key}) : super(key: key);
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
String nik = "";
String nama = "";
Future<bool> _onWillPop() {
SweetAlert.show(context,
subtitle: "Exit Aplications",
style: SweetAlertStyle.confirm,
showCancelButton: true, onPress: (bool isConfirm) {
if (isConfirm) {
SweetAlert.show(context,
subtitle: "Exit...", style: SweetAlertStyle.loading);
new Future.delayed(new Duration(seconds: 2), () {
exit(0);
});
} else {
Navigator.of(context).pop(false);
}
// return false to keep dialog
return false;
});
}
Future _cekLogin() async {
//SHAREDPREFERENCES
SharedPreferences pref = await SharedPreferences.getInstance();
if (pref.getBool("isLogin") == false) {
// Navigator.push(
// context, MaterialPageRoute(builder: (context) => new Login()));
Navigator.pushReplacementNamed(context, "/login");
}
}
Future _Logout() async {
//SHAREDPREFERENCES
SharedPreferences pref = await SharedPreferences.getInstance();
pref.setBool("isLogin", false);
pref.setString("dataMessage", "");
pref.setString("karNik", "");
pref.setString("karNama", "");
Navigator.push(
context, MaterialPageRoute(builder: (context) => new Login()));
}
Future _cekUser() async {
//SHAREDPREFERENCES
SharedPreferences pref = await SharedPreferences.getInstance();
if (pref.getString("karNik") != null) {
setState(() {
nik = pref.getString("karNik");
nama = pref.getString("karNama");
});
}
}
@override
void initState() {
super.initState();
_cekLogin();
_cekUser();
}
@override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: _onWillPop,
child: Scaffold(
appBar: AppBar(
leading: Icon(Icons.android),
title: Text("Halaman Home"),
),
body: Center(
child: Column(
children: <Widget>[
//TEXT
Text("Welcome :" + nik + " - " + nama),
//BUTTON
_buttonLogout(context),
],
)),
),
);
}
Widget _buttonLogout(BuildContext context) {
return Padding(
padding: EdgeInsets.all(8.0),
child: new InkWell(
onTap: () {
SweetAlert.show(context,
subtitle: "Logout...", style: SweetAlertStyle.loading);
new Future.delayed(new Duration(seconds: 2), () {
_Logout();
});
},
child: new Container(
//width: 100.0,
height: 50.0,
decoration: new BoxDecoration(
color: Colors.blueAccent,
border: new Border.all(color: Colors.white, width: 2.0),
borderRadius: new BorderRadius.circular(10.0),
),
child: new Center(
child: new Text(
'Logout',
style: new TextStyle(fontSize: 18.0, color: Colors.white),
),
),
),
),
);
}
}
Preview
meetap_flutter_basic_07
By Maulana Ilham
meetap_flutter_basic_07
meetap_flutter_basic_07
- 776