Flutter Rest API Integration with Login and Registration pages

mouli150388

mouli150388

Posted on September 11, 2022

Flutter Rest API Integration with Login and Registration pages

Flutter is hybrid open source framework introduced by google. With flutter we can develope crosplatform applications like Android,ios, Linux, macos,Windows with sinlge codebase.

In this example we are going to cover rest API integration in Flutter.

  • Building the Flutter app
  • Interfacing with the REST api
  • Authentication
  • Create User Account
  • Building the UI
  • Login screen
  • Signup Screen
  • Home Screen
  • Complete Code of the Rest API Integration

This example contains the below backend PHP files

  • mysqli_connect.php
  • login.php
  • registration.php

Front end having the below page

  • signin.dart
  • signup.dart
  • home.dart
  • main.dart Flutter Rest API Integration with Login and Registartion pages

Service Layer This flutter login example will communicate with backend system, so in our application folder create a file api.dart and add server endpoints (API URLS)

We have created a file api.dart file and added all API information

const String ROOT="http://tutionteacher.rrtutors.com";
const String REGISTRATION="$ROOT/api/registration.php";
const String LOGIN="$ROOT/api/login.php";

Flutter User Authentication

Here is the code for authentication api integration in flutter

`login(email,password) async
{
Map data = {
'email': email,
'password': password
};
print(data.toString());
final response= await http.post(
Uri.parse(LOGIN),
headers: {
"Accept": "application/json",
"Content-Type": "application/x-www-form-urlencoded"
},

    body: data,
    encoding: Encoding.getByName("utf-8")
)  ;
setState(() {
  isLoading=false;
});
if (response.statusCode == 200) {
  Map<String,dynamic>resposne=jsonDecode(response.body);
  if(!resposne['error'])
  {
    Map<String,dynamic>user=resposne['data'];
    print(" User name ${user['id']}");
    savePref(1,user['name'],user['email'],user['id']);
    Navigator.pushReplacementNamed(context, "/home");
  }else{
    print(" ${resposne['message']}");
  }
  scaffoldMessenger.showSnackBar(SnackBar(content:Text("${resposne['message']}")));

} else {
  scaffoldMessenger.showSnackBar(SnackBar(content:Text("Please try again!")));
}
Enter fullscreen mode Exit fullscreen mode

}
savePref(int value, String name, String email, int id) async {
SharedPreferences preferences = await SharedPreferences.getInstance();

  preferences.setInt("value", value);
  preferences.setString("name", name);
  preferences.setString("email", email);
  preferences.setString("id", id.toString());
  preferences.commit();
Enter fullscreen mode Exit fullscreen mode

}
}`

In the above method email and password are the request params, these params we are passing the the http post method by add inside map to body attribute

Map data = { 'email': email, 'password': password };

After calling the login api, we are check the response, if the response code received as 200 response.statusCode == 200 then we need to JSON Parse to check the user details

In this we are doing the JSON Parse by jsonDecode method

`Mapresponse=jsonDecode(response.body);

if(!response['error']) {

Mapuser=response['data'];

print(" User name ${user['id']}");

savePref(1,user['name'],user['email'],user['id']);

Navigator.pushReplacementNamed(context, "/home");

}

else{

print(" ${resposne['message']}");

}`

User Session management

After login api success response we are saving the user session in Shared Preference. This data we can use it when we start the application. If the session data available we will navigate user directly homescreen

Save User Session:

`savePref(int value, String name, String email, int id) async {

SharedPreferences preferences = await SharedPreferences.getInstance();

preferences.setInt("value", value);

preferences.setString("name", name);

preferences.setString("email", email);

preferences.setString("id", id.toString());

preferences.commit();

}`

Validate user session:

`var _loginStatus=0; getPref() async {

SharedPreferences preferences = await SharedPreferences.getInstance();

setState(() {

_loginStatus = preferences.getInt("value")!;

});

}

}`

Download complete source code for Flutter Rest API Integration with login and registarion pages

💖 💪 🙅 🚩
mouli150388
mouli150388

Posted on September 11, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related