Thursday 17 August 2023

How to implement the pagination in flutter?


class PaginationDemo extends StatefulWidget {

  const PaginationDemo({Key? key}) : super(key: key);


  @override

  _PaginationDemoState createState() => _PaginationDemoState();

}


class _PaginationDemoState extends State<PaginationDemo> implements PaginationInterFace{

  PaginationPresenter? paginationPresenter;

  int limit=10;

  int page=1;

  List<AllPostData> allPosts=[];

  bool isLoading =false;


  @override

  void initState() {

 paginationPresenter=PaginationPresenter(this);

 setState(() {

 isLoading=true;

 });

 paginationPresenter?.doGetData(page.toString(),limit.toString());

  super.initState();

  }

  @override

  Widget build(BuildContext context) {

  returnScaffold(

  body: Stack(

  children: [

  NotificationListener<ScrollNotification>(

  onNotification: _onNotification,

  child: ListView.builder(

  itemCount:allPosts.length,

  itemBuilder:

  (BuildContext

  context,

  int index){

  return Container(

  margin: EdgeInsets.all(40),

  child: Text(allPosts[index].caption.toString()));

  }


  ),

  ),

  Visibility(

  visible: isLoading,

  child: Container(

  color: Colors.transparent,

  width:MediaQuery.of(context).size.width,

  height:MediaQuery.of(context).size.height,

  alignment: Alignment.center,

  child: const CircularProgressIndicator(

  valueColor:

  AlwaysStoppedAnimation<Color>(Colors.black54),

  ),

  ))

  ],

  ),

  );

  }

  bool _onNotification(ScrollNotification notification) {

  if (notification is ScrollEndNotification &&

  notification.metrics.pixels >=

  notification.metrics.maxScrollExtent - 200) {

  fetchData();

  }

  return true;

  }


  Future<void> fetchData() async {

  if (isLoading) return;

  setState(() {

  isLoading = true;

  });

  // Simulating API request with a delay

  await Future.delayed(Duration(seconds: 2));

  int count=page++;

  paginationPresenter?.doGetData(count.toString(),limit.toString());

  }


  @override

  onError(String msg, int status) {

  setState(() {

  isLoading=false;

  });

  if (kDebugMode) {

  print("onError${msg}");

  }

  }


  @override

  onSuccess(AllPostResponse allPostResponse) {

  setState(() {

  isLoading=false;

  });

  if (kDebugMode) {

  print("Success${allPostResponse.status}");

  }

  if (allPostResponse.status == 200) {

  allPosts.addAll(allPostResponse.data!);

  }

  }

}




/////// add parameter in int bool etc

Future<AllPostResponse> registerAPI(String isPhone,) async {

 Map<String, dynamic> requestBody = {

   "isPhone":false,};

  String jsonBody=json.encode(requestBody);

  // Set the headers

  Map<String, String> headers = {

  'Content-Type': 'application/json',

  };

  return _netUtil.postApi("", body: jsonBody,headers: headers).then((dynamic res) {

  return AllPostResponse.fromJson(res);

  });

  

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);

}


}