Im new to flutter and currently work as an intern in a small company, I'm trying to get API from laravel and try to login in flutter. Is there anyone can assist me to have a look on my code? I will write them below.
I'm trying to test it without token, but on online tutorial everyone is having token.
api.dart
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';
class Network{
final String _url = 'http://192.168.0.138:8000/api/';
var token;
_getToken() async {
SharedPreferences localStorage = await SharedPreferences.getInstance();
token = jsonDecode(localStorage.getString('token'))['token'];
}
authData(data, apiUrl) async {
var fullUrl = _url + apiUrl;
return await http.post(
fullUrl,
body: jsonEncode(data),
headers: _setHeaders()
);
}
getData(apiUrl) async {
var fullUrl = _url + apiUrl;
await _getToken();
return await http.get(
fullUrl,
headers: _setHeaders()
);
}
_setHeaders() => {
'Content-type' : 'application/json',
'Accept' : 'application/json',
'Authorization' : 'Bearer $token'
};
}
Login_Screen
import 'package:ezymember/screens/home_screen.dart';
import 'package:ezymember/screens/register_screen.dart';
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:ezymember/network_utils/api.dart';
import 'package:shared_preferences/shared_preferences.dart';
class LoginScreen extends StatefulWidget {
const LoginScreen({Key key}) : super(key: key);
@override
_LoginScreenState createState() => _LoginScreenState();
}
class _LoginScreenState extends State<LoginScreen> {
bool _isLoading = false;
final _formKey = GlobalKey<FormState>();
var member_email;
var member_password;
final _scaffoldKey = GlobalKey<ScaffoldState>();
_showMsg(msg) {
final snackBar = SnackBar(
content: Text(msg),
action: SnackBarAction(
label: 'Close',
onPressed: () {
// Some code to undo the change!
},
),
);
_scaffoldKey.currentState.showSnackBar(snackBar);
}
@override
Widget build(BuildContext context) {
return Scaffold(
key: _scaffoldKey,
body: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Stack(
children: <Widget>[
Container(
padding: const EdgeInsets.fromLTRB(15.0, 110.0, 0.0, 0.0),
child: const Text('Hello',
style:
TextStyle(fontSize: 80.0, fontWeight: FontWeight.bold)),
),
Container(
padding: const EdgeInsets.fromLTRB(16.0, 175.0, 0.0, 0.0),
child: const Text('There',
style:
TextStyle(fontSize: 80.0, fontWeight: FontWeight.bold)),
),
Container(
padding: const EdgeInsets.fromLTRB(220.0, 175.0, 0.0, 0.0),
child: const Text('.',
style: TextStyle(
fontSize: 80.0,
fontWeight: FontWeight.bold,
color: Colors.blue)),
)
],
),
Container(
padding: const EdgeInsets.only(top: 35.0, left: 20.0, right: 20.0),
child: Form(
key: _formKey,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
TextFormField(
keyboardType: TextInputType.text,
decoration: const InputDecoration(
labelText: 'EMAIL',
labelStyle: TextStyle(
fontFamily: 'Montserrat',
fontWeight: FontWeight.bold,
color: Colors.grey),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.blue)),
),
validator: (emailValue) {
if (emailValue.isEmpty) {
return 'Please enter email';
}
member_email = emailValue;
return null;
},
),
TextFormField(
keyboardType: TextInputType.text,
decoration: const InputDecoration(
labelText: 'PASSWORD',
labelStyle: TextStyle(
fontFamily: 'Montserrat',
fontWeight: FontWeight.bold,
color: Colors.grey),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.blue)),
),
validator: (passwordValue) {
if (passwordValue.isEmpty) {
return 'Please Enter Password';
}
member_password = passwordValue;
return null;
},
),
Padding(
padding: const EdgeInsets.all(10.0),
child: FlatButton(
child: Padding(
padding: const EdgeInsets.only(
top: 8, bottom: 8, left: 10, right: 10),
child: Text(
_isLoading ? 'Proccessing...' : 'Login',
textDirection: TextDirection.ltr,
style: const TextStyle(
color: Colors.white,
fontSize: 20.0,
decoration: TextDecoration.none,
fontWeight: FontWeight.normal,
),
),
),
color: Colors.blue,
disabledColor: Colors.grey,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20.0)),
onPressed: () {
if (_formKey.currentState.validate()) {
_login();
}
},
),
),
],
),
),
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'New to EzyMember ?',
style: TextStyle(fontFamily: 'Montserrat'),
),
const SizedBox(width: 5.0),
InkWell(
onTap: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => RegisterPage()));
},
child: const Text(
'Register',
style: TextStyle(
color: Colors.blue,
fontFamily: 'Montserrat',
fontWeight: FontWeight.bold,
decoration: TextDecoration.underline),
),
),
],
),
],
),
),
);
}
void _login() async {
setState(() {
_isLoading = true;
});
var data = {'email': member_email, 'password': member_password};
var res = await Network().authData(data, '/login');
var body = json.decode(res.body);
if (body['success']) {
SharedPreferences localStorage = await SharedPreferences.getInstance();
localStorage.setString('token', json.encode(body['token']));
localStorage.setString('user', json.encode(body['user']));
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const HomeScreen()),
);
} else {
_showMsg(body['message']);
}
setState(() {
_isLoading = false;
});
}
}