Tuesday 8 August 2023

 How we can implement the API in flutter project?

We need to create project in android studio or visual studio and also need to make the below class for API call.



Need to add the below Library in pubspec.yaml:-

http:




Login Screen


class LoginScreen extends StatefulWidget {

  LoginScreen({Key? key}) : super(key: key);

  @override

  State<LoginScreen> createState() => _LoginScreenState();

}

class _LoginScreenState extends State<LoginScreen> implements LoginInterface  {

//Init presenter

  LoginPresenter? loginPresenter;



  @override

  void initState() {

//Declare presenter

  loginPresenter=LoginPresenter(this);


//Calling the API

 loginPresenter!.doLogin(“Email”, “Password”);

    super.initState();

  }


@override

onSuccess(LoginResponse response) {

//LoginResponse:- You need to make model according to API response 

}



@override

onError(String msg,int status) {

 

}


}



Interface:- 

abstract class LoginInterface {

  onSuccessRespnse(LoginResponse response);

 //LoginResponse(Need to make response according to API)

  onError(String msg,int status);

}


class LoginPresenter {

  LoginInterface _view;

  RestDatasource api = new RestDatasource();

  LoginPresenter(this._view);


  doLogin(String email, String password) {

    api.login(email,password)

        .then((LoginResponse user) {

      if (user.status == 200) {

        _view.onSuccessRespnse(user);

      }

      else if (user.status == 400) {

        _view.onError(user.message!,user.status!);

      }

      else if (user.status == 203) {

        _view.onError(user.message!,user.status!);

      }

      else {

        _view.onError(user.message.toString(),user.status!);

      }

    }).catchError((Object error) => _view.onError(error.toString(),500));


  }


}




Constant =>  Endpoints


class Endpoints {

  Endpoints._();

  // base url

  static final String baseUrl = Endpoints._getBaseURL();

  static String _getBaseURL() {

     return ‘Your’ Base URL;


  }

  static final BASE_URL = baseUrl;

  // login endpoints

  static final LOGIN_URL = “Your End URL”;

}



RestDatasource


class RestDatasource {

  NetworkUtil _netUtil = new NetworkUtil();


 Future<LoginResponse> login(String email, String password) {

  return _netUtil.postApi(Endpoints.LOGIN_URL, body: {

    “Your Parameter”: email,

    "Your Parameter”: password,

  }).then((dynamic res) {

    return LoginResponse.fromJson(res);

  });

}

}



Future<MediaResponse> uploadMediaFile(File photo) {

  return _netUtil

      .multipartVideoImage(

      "Your URL",

          {

            "Authorization": "Your Token",

          },

          photo)

      .then((dynamic res) {

    return MediaResponse.fromJson(res);

  });

}





NetworkUtils:- 


class NetworkUtil {

  //Next three lines makes this class a Singleton

  static NetworkUtil _instance = new NetworkUtil.internal();


  NetworkUtil.internal();


  factory NetworkUtil() => _instance;

  final JsonDecoder _decoder = new JsonDecoder();



  Future<dynamic> get(String url, Map<String, String> headers) {

    return http.get(Uri.parse(url), headers: {

      "Authorization": “”,

    }).then((http.Response response) {

      final String res = response.body;

      final int statusCode = response.statusCode;

      if (statusCode == 203 ||

          statusCode == 201 ||

          statusCode == 400 ||

          json == null) {

        //  throw new Exception("Error while fetching data");

      }

      return _decoder.convert(res);

    });

  }

  



  Future<dynamic> postApi(String url, {Map? headers, body, encoding}) async {

    return http

        .post(Uri.parse(url),

        body: body,

        encoding: encoding)

        .then((http.Response response) {

      final String res = response.body;

      final int statusCode = response.statusCode;

      if (statusCode == 203 || statusCode == 201 ||

          statusCode == 400 ||

          json == null) {

        //throw new Exception("Error while fetching data");

      }

      return _decoder.convert(res);

    });

  }


Future<dynamic> multipartVideoImage(String url,

    Map<String, String> headers, File fileName) async {

  var request = http.MultipartRequest('POST', Uri.parse(url));

  request.headers.addAll(headers);

  if (fileName.path.isNotEmpty) {

    MediaType? contentTypes;

    if (fileName.path.contains(".mp4") || fileName.path.contains(".m4a")) {

      contentTypes = MediaType.parse("video/mp4");

    }

    else

    if (fileName.path.contains(".png") || fileName.path.contains(".jpg") ||

        fileName.path.contains(".jpeg")) {

      contentTypes = MediaType.parse("image/png");

    }

    

    var multipartFile = await http.MultipartFile.fromPath(

      "images", fileName.path, contentType: contentTypes,

    );

    request.files.add(multipartFile);

  }

  var res = await request.send();

  var result = await http.Response.fromStream(res);

  return _decoder.convert(result.body);

}


}

No comments:

Post a Comment