Flutter Rest API Integration

In this Flutter Rest API Integration example we will build user Registration and Authentication with Backend System. Here we are using the Backend Authentication with PHP Registration and Login APIs. In the App side we are maintain the User Authentication status with Shared Preferences. Previous article we have learned REST API Integration in Flutter with Retrofit library and we also updated dependencies with null safety feature. If we have to declare variables before accessing we need to apply late modifier to that variable.

Showing the snackbar with Scaffold is deprecated here we are showing the snackbar with scaffoldMessengerState

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

We would need to make HTTP calls and persist data locally, so add two additional packages to pubsec.yaml as well

dev_dependencies:
  flutter_test:
    sdk: flutter
  http: ^0.13.3
  flutter_datetime_picker: ^1.5.1
  intl: ^0.17.0
  webview_flutter: ^2.0.9
  shared_preferences: ^2.0.6

Call Rest API with http post request

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!")));
    }


  }

How to make email validation in flutter?

In this REST API integration email validation is made by using Reg expression like below, we can also validate form fields by using Flutter Form Buider

var reg=RegExp(r"^[a-zA-Z0-9.a-zA-Z0-9.!#$%&'*+-/=?^_`{|}~]+@[a-zA-Z0-9]+\.[a-zA-Z]+");

reg.hasMatch(_emailController.text)

In the above we have used http package to make rest api calls. Here Rest API integration with Retrofit to handle response and parse json data to model class

Download source code for
Flutter Rest API Integration with Login and registration

27