0

how are you ?

i have laravel backend with passport auth and now i want to link it with my mobile app in flutter

i want to make the auth but i'm new in flutter and i don't know how to start to do this

first i make my models

this is my first model login.dart

class Login {
  final String login;
  final String password;

  Login (this.login,this.password);
}

my second model is register.dart

class Register {
  final String email;
  final String name;
  final String mobile;
  final String password;

  Register(
    this.email,
    this.name,
    this.mobile,
    this.password,
  );
}

and this is User model

class User {
  final int id ;
  final int active ;
  final int confirmed ;
  final String mobile  ;
  final String name ;
  final String email ;
  final String confirmation_code ;

 User(this.id,this.active,this.confirmed,this.mobile,this.name,this.email,this.confirmation_code);


}

this is my Auth Response Model

import './User.dart';

class AuthResponse {
  final String token;
  final User user;

  AuthResponse(
    this.user, this.token
  );


}

but now i don't know how to make the auth and link it with these models so can any one help please

thanks


New codes

my login page code

import 'dart:async';

import 'package:flutter/material.dart';

import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';

import 'package:flutter/services.dart';

import '../../common/apifunctions/requestLoginAPI.dart';


import 'package:gradient_widgets/gradient_widgets.dart';



class UserLoginPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _UserLoginPage();
  }
}

class _UserLoginPage extends State<UserLoginPage> {
  final TextEditingController _mobileController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();



  @override
  void initState() {
    super.initState();
    _saveCurrentRoute('/UserLogin');
  }

  _saveCurrentRoute(String lastRoute) async {
    SharedPreferences preferences = await SharedPreferences.getInstance();
    await preferences.setString('LastScreenRoute', lastRoute);
  }

  void _gloginButton() {
    Navigator.pushReplacementNamed(context, '/Home');
  }

  void _registerButton() {
    Navigator.pushNamed(context, '/UserRegister');
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
        onWillPop: () {
          if (Navigator.canPop(context)) {
            Navigator.of(context).pushNamedAndRemoveUntil(
                '/Home', (Route<dynamic> route) => false);
          } else {
            Navigator.of(context).pushReplacementNamed('/Home');
          }
        },
        child: Scaffold(
          body: Column(
            children: <Widget>[
              Image.asset('assets/img/LRUI.png'),
              Form(
                child: Container(
                  //padding: EdgeInsets.only(top: 100.0),
                  margin: EdgeInsets.all(35.0),
                  child: Center(
                    child: Center(
                      child: SingleChildScrollView(
                        child: Column(
                          children: <Widget>[
                            SizedBox(
                              height: 99.0,
                            ),
                            TextFormField(
                              controller: _mobileController,
                              decoration: InputDecoration(
                                labelText: 'رقم الجوال',
                                hintText: "رقم الجوال يجب أن يكون عشر ارقام",
                              ),
                              style: TextStyle(
                                fontSize: 18.0,
                                color: Colors.grey,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                            SizedBox(height: 11.0),
                            TextFormField(
                              controller: _passwordController,
                              decoration: InputDecoration(
                                labelText: 'الرقم السري',
                              ),
                              obscureText: true,
                              style: TextStyle(
                                fontSize: 18.0,
                                color: Colors.grey,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                            SizedBox(
                              height: 40.0,
                            ),
                            GradientButton(
                              gradient: const LinearGradient(
                                begin: Alignment.topLeft,
                                end: Alignment.bottomCenter,
                                colors: const <Color>[
                                  Color(0xff4caf4e),
                                  Color(0xff71c071),
                                ],
                              ),
                              callback: () {
                                SystemChannels.textInput
                                    .invokeMethod('TextInput.hide');
                                requestLoginAPI(context, _mobileController.text,
                                    _passwordController.text);
                              },
                              textStyle: TextStyle(
                                  color: Colors.white, fontSize: 16.0),
                              shapeRadius: BorderRadius.circular(10.0),
                              child: Text(
                                "دخول",
                              ),
                              increaseHeightBy: 20.0,
                              increaseWidthBy: 140.0,
                            ),
                            SizedBox(
                              height: 35.0,
                            ),
                            FlatButton(
                              child: Text('دخول كضيف'),
                              onPressed: _gloginButton,
                            ),
                            FlatButton(
                              child: Text('تسجيل حساب جديد'),
                              onPressed: _registerButton,
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),
                ),
              ),
            ],
          ),
        ));
  }
}

and this is my my Api function code for request login

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import '../functions/ saveCurrentLogin.dart';
import '../functions/showDialog.dart';
import 'dart:convert';

import '../../Models/Login.dart';
import '../../Models/User.dart';
import '../../Models/AuthResponse.dart';

Future<Login> requestLoginAPI(BuildContext context, String login, String password) async {
  final url = "http://188.166.172.146/Blooming/public/api/login";

  Map<String, String> body = {
    'login': login,
    'password': password,
  };

  final response = await http.post(
    url,
    body: body,
  );

  if (response.statusCode == 200) {
    final responseJson = json.decode(response.body);
    var token = new AuthResponse.fromJson(responseJson);

    saveCurrentLogin(responseJson);
    Navigator.of(context).pushReplacementNamed('/About');
      



    return Login.fromJson(responseJson);
  } else {
    final responseJson = json.decode(response.body);

    saveCurrentLogin(responseJson);
    showDialogSingleButton(context, "خطأ", "تأكد من معلومات الدخول", "موافق");

    return null;
  }
}

this is my save current login function code

import 'package:shared_preferences/shared_preferences.dart';


import '../../Models/AuthResponse.dart';
import '../../Models/User.dart';

saveCurrentLogin(Map responseJson) async {
  SharedPreferences preferences = await SharedPreferences.getInstance();


  var token = (responseJson != null && !responseJson.isEmpty) ? AuthResponse.fromJson(responseJson).token : "";

  var id = (responseJson != null && !responseJson.isEmpty) ? User.fromJson(responseJson).id : 0;
  var name = (responseJson != null && !responseJson.isEmpty) ? User.fromJson(responseJson).name : "";
  var email = (responseJson != null && !responseJson.isEmpty) ? User.fromJson(responseJson).email : "";
  var mobile = (responseJson != null && !responseJson.isEmpty) ? User.fromJson(responseJson).mobile : "";
  var active = (responseJson != null && !responseJson.isEmpty) ? User.fromJson(responseJson).active : 0;
  var confirmation_code = (responseJson != null && !responseJson.isEmpty) ? User.fromJson(responseJson).confirmation_code : "";
  var confirmed = (responseJson != null && !responseJson.isEmpty) ? User.fromJson(responseJson).confirmed : 0;

  await preferences.setString('token', (token != null && token.length > 0) ? token : "");

  await preferences.setInt('id', (id != null && id > 0) ? id : 0);
  await preferences.setString('name', (name != null && name.length > 0) ? name : ""); 
  await preferences.setString('email', (email != null && email.length > 0) ? email : ""); 
  await preferences.setString('mobile', (mobile != null && mobile.length > 0) ? mobile : ""); 
  await preferences.setInt('active', (active != null && active > 0) ? active : 0);
  await preferences.setString('confirmation_code', (confirmation_code != null && confirmation_code.length > 0) ? confirmation_code : ""); 
  await preferences.setInt('confirmed', (confirmed != null && confirmed > 0) ? confirmed : 0);
  

}

this is get token function code

import 'package:shared_preferences/shared_preferences.dart';

getToken() async {
  SharedPreferences preferences = await SharedPreferences.getInstance();

  String getToken = await preferences.getString("token");
  return getToken;
}

this is the new login model

class Login {
  final String login;
  final String password;


  Login(this.login, this.password);

  Login.fromJson(Map<String, dynamic> json)
      : login = json['login'],
        password = json['password'];


}

this is auth response model

import './User.dart';

class AuthResponse {
  final String token;
  User user;

  AuthResponse({
    this.token,
    this.user,
  });

factory AuthResponse.fromJson(Map<String, dynamic> parsedJson){
  return AuthResponse(
    token: parsedJson['token'],
    user: User.fromJson(parsedJson['user'])
  );
}
  

  Map<String, dynamic> toJson() => {
        'token': token,
        'user':user,
      };
}

this is my User model

class User {
  final int id;
  final String name;
  final String email;
  final String mobile;
  final int active;
  final String confirmation_code;
  final int confirmed;

  User({
    this.id,
    this.name,
    this.email,
    this.mobile,
    this.active,
    this.confirmation_code,
    this.confirmed,
  });

  factory User.fromJson(Map<String, dynamic> json) {
    return User(
      id: json['id'],
      name: json['name'],
      email: json['email'],
      mobile: json['mobile'],
      active: json['active'],
      confirmation_code: json['confirmation_code'],
      confirmed: json['confirmed'],
    );
  }

  Map<String, dynamic> toJson() => {
        'id': id,
        'name': name,
        'email':email,
        'mobile':mobile,
        'active':active,
        'confirmation_code':confirmation_code,
        'confirmed':confirmed,
      };
}
1
  • is this code working ? Commented Dec 17, 2020 at 15:59

1 Answer 1

2

the best way to do this by using shared preferences

  • 1 - you need to install dependence (see the link)
  • 2 - make your "http" request with your server to get the "auth key"
  • 3 - create tow "shared preferences" keys :

and give the first one the name of "auth_key" to store the authentication key and save the other one as "bool" data type, give it the name "is_login" now in the main function of the dart, check the parameter "is_login", if its true , countenu to (home page , account ... etc), otherwise take it to the login widget

dart code to set the two keys

Future<void> setUserLogin(String auth_token) async{
    SharedPreferences pref = await SharedPreferences.getInstance();
    pref.setString("auth_token", auth_token);
    pref.setBool("is_login", true);
 }

check if login:

  Future<bool> isUserLogin() async{
    SharedPreferences pref = await SharedPreferences.getInstance();
    return pref.getBool("is_login");
 }

get the auth key:

  Future<bool> isUserLogin() async{
    SharedPreferences pref = await SharedPreferences.getInstance();
    return pref.getString("auth_token");
 }

logout method

  Future<void> logout() async{
    SharedPreferences pref = await SharedPreferences.getInstance();
    pref.remove("auth_key");
   pref.remove("is_login");
 }

I just give you an example of how to do it, you need to read more about "SharedPreferences" at the link below to know more about there is another techniques like save data to sql, but its more complicated, and I guess its less secure (cuz there is many root apps working as sqlite browsers)

Sign up to request clarification or add additional context in comments.

11 Comments

i understand your point but i don't how use the sharedpreferences i follow this documentation and the login is worked but now my problem how to keep the user login after i rerun the app medium.com/flutterpub/… he used here SharedPreferences and its not working with me
@Abdullah can you post your code ? (try to abstract it as you can) to help you
i add all my new codes in the post under New codes line
am sorry :) i didnt notice oky lets divide the issue into pieces at the first run your app , then copy and paste the "run logs" to see i notice somthing in this part of your code if (response.statusCode == 200) { final responseJson = json.decode(response.body); var token = new AuthResponse.fromJson(responseJson); saveCurrentLogin(responseJson); Navigator.of(context).pushReplacementNamed('/About'); << here return Login.fromJson(responseJson); } Navigator.of(context).pushReplacementNamed('/About'); well stop the method execution before its end
your code is a full of bugs ! and unlogical operations that well make an interrupts in many methods you need to dismantling it into small pieces
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.