2019-05-08 18:54:14 +00:00
import ' dart:async ' ;
import ' dart:convert ' ;
import ' package:flutter/material.dart ' ;
import ' package:http/http.dart ' as http ;
import ' package:local_spend/common/functions/save_current_login.dart ' ;
import ' package:local_spend/model/json/login_model.dart ' ;
2019-08-16 13:21:21 +00:00
Future < void > _incorrectDialog ( BuildContext context , bool isLoginWrong ) async {
2019-08-12 14:18:01 +00:00
return showDialog < void > (
context: context ,
barrierDismissible: true ,
builder: ( BuildContext context ) {
2019-08-20 12:54:45 +00:00
return AnimatedContainer (
duration: Duration ( seconds: 2 ) ,
child : AlertDialog (
title: Text ( " Uh-oh! " ) ,
content: Text ( isLoginWrong ? " Incorrect login details. Please try again. " : " Our servers are having issues at the moment; sorry for the inconvenience. Please try again later. " ) ,
actions: < Widget > [
FlatButton (
child: Text ( ' OK ' ) ,
onPressed: ( ) {
Navigator . of ( context ) . pop ( ) ;
} ,
) ,
] ,
) ,
2019-08-12 14:18:01 +00:00
) ;
} ,
) ;
}
2019-08-20 12:54:45 +00:00
Future < LoginModel > requestLoginAPI ( BuildContext context , String email , String password ) async {
final url = " https://dev.localspend.co.uk/api/login " ;
2019-05-08 18:54:14 +00:00
Map < String , String > body = {
' email ' : email ,
' password ' : password ,
} ;
2019-07-16 11:09:10 +00:00
// debugPrint('$body');
2019-05-08 18:54:14 +00:00
2019-08-16 13:21:21 +00:00
try {
final response = await http . post (
url ,
body: json . encode ( body ) ,
2019-08-20 12:54:45 +00:00
) . timeout ( Duration ( seconds: 5 ) ) ;
2019-05-08 18:54:14 +00:00
2019-08-16 13:21:21 +00:00
if ( response . statusCode = = 200 ) {
final responseJson = json . decode ( response . body ) ;
2019-05-08 18:54:14 +00:00
2019-08-16 13:21:21 +00:00
saveCurrentLogin ( responseJson , body [ " email " ] ) ;
Navigator . of ( context ) . pushReplacementNamed ( ' /HomePage ' ) ;
2019-05-08 18:54:14 +00:00
2019-08-16 13:21:21 +00:00
return LoginModel . fromJson ( responseJson ) ;
} else {
final responseJson = json . decode ( response . body ) ;
2019-07-15 11:09:10 +00:00
2019-08-16 13:21:21 +00:00
saveCurrentLogin ( responseJson , body [ " email " ] ) ;
2019-05-08 18:54:14 +00:00
2019-08-16 13:21:21 +00:00
_incorrectDialog ( context , true ) ;
2019-07-16 11:09:10 +00:00
2019-08-16 13:21:21 +00:00
return null ;
}
2019-08-20 12:54:45 +00:00
} on TimeoutException catch ( _ ) {
_incorrectDialog ( context , false ) ;
2019-08-16 13:23:03 +00:00
} catch ( error ) {
debugPrint ( error . toString ( ) ) ;
2019-08-16 13:21:21 +00:00
_incorrectDialog ( context , false ) ;
2019-05-08 18:54:14 +00:00
}
}
2019-08-16 13:21:21 +00:00